home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / libg_261.zip / libg_261 / librx / rx.c < prev    next >
C/C++ Source or Header  |  1994-10-20  |  177KB  |  7,160 lines

  1. /*    Copyright (C) 1992, 1993 Free Software Foundation, Inc.
  2.  
  3. This file is part of the librx library.
  4.  
  5. Librx is free software; you can redistribute it and/or modify it under
  6. the terms of the GNU Library General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9.  
  10. Librx is distributed in the hope that it will be useful, but WITHOUT
  11. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12. FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13. for more details.
  14.  
  15. You should have received a copy of the GNU Library General Public
  16. License along with this software; see the file COPYING.LIB.  If not,
  17. write to the Free Software Foundation, 675 Mass Ave, Cambridge, MA
  18. 02139, USA.  */
  19.  
  20. /* NOTE!!!  AIX is so losing it requires this to be the first thing in the 
  21.  * file. 
  22.  * Do not put ANYTHING before it!  
  23.  */
  24. #if !defined (__GNUC__) && defined (_AIX)
  25.  #pragma alloca
  26. #endif
  27.  
  28. char rx_version_string[] = "GNU Rx version 0.06";
  29.  
  30.             /* ``Too hard!''
  31.              *        -- anon.
  32.              */
  33.  
  34.  
  35. #include <stdio.h>
  36. #include <ctype.h>
  37. #ifndef isgraph
  38. #define isgraph(c) (isprint (c) && !isspace (c))
  39. #endif
  40. #ifndef isblank
  41. #define isblank(c) ((c) == ' ' || (c) == '\t')
  42. #endif
  43.  
  44. #include <sys/types.h>
  45.  
  46. #undef MAX
  47. #undef MIN
  48. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  49. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  50.  
  51. typedef char boolean;
  52. #define false 0
  53. #define true 1
  54.  
  55. #ifndef RX_DECL
  56. #define RX_DECL static
  57. #endif
  58.  
  59. #ifndef __GCC__
  60. #undef __inline__
  61. #define __inline__
  62. #endif
  63.  
  64. /* Emacs already defines alloca, sometimes.  */
  65. #ifndef alloca
  66.  
  67. /* Make alloca work the best possible way.  */
  68. #ifdef __GNUC__
  69. #define alloca __builtin_alloca
  70. #else /* not __GNUC__ */
  71. #if HAVE_ALLOCA_H
  72. #include <alloca.h>
  73. #else /* not __GNUC__ or HAVE_ALLOCA_H */
  74. #ifndef _AIX /* Already did AIX, up at the top.  */
  75. char *alloca ();
  76. #endif /* not _AIX */
  77. #endif /* not HAVE_ALLOCA_H */ 
  78. #endif /* not __GNUC__ */
  79.  
  80. #endif /* not alloca */
  81.  
  82. /* Memory management and stuff for emacs. */
  83.  
  84. #define CHARBITS 8
  85. #define remalloc(M, S) (M ? realloc (M, S) : malloc (S))
  86.  
  87.  
  88. /* Should we use malloc or alloca?  If REGEX_MALLOC is not defined, we
  89.  * use `alloca' instead of `malloc' for the backtracking stack.
  90.  *
  91.  * Emacs will die miserably if we don't do this.
  92.  */
  93.  
  94. #ifdef REGEX_MALLOC
  95. #define REGEX_ALLOCATE malloc
  96. #else /* not REGEX_MALLOC  */
  97. #define REGEX_ALLOCATE alloca
  98. #endif /* not REGEX_MALLOC */
  99.  
  100. #ifdef RX_WANT_RX_DEFS
  101. #define RX_DECL extern
  102. #define RX_DEF_QUAL 
  103. #else
  104. #define RX_WANT_RX_DEFS
  105. #define RX_DECL static
  106. #define RX_DEF_QUAL static
  107. #endif
  108. #include "rx.h"
  109. #undef RX_DECL
  110. #define RX_DECL RX_DEF_QUAL
  111.  
  112.  
  113. #ifndef emacs
  114.  
  115. #ifdef SYNTAX_TABLE
  116. extern char *re_syntax_table;
  117. #else /* not SYNTAX_TABLE */
  118.  
  119. /* RX_DECL char re_syntax_table[CHAR_SET_SIZE]; */
  120.  
  121. #ifdef __STDC__
  122. static void
  123. init_syntax_once (void)
  124. #else
  125. static void
  126. init_syntax_once ()
  127. #endif
  128. {
  129.    register int c;
  130.    static int done = 0;
  131.  
  132.    if (done)
  133.      return;
  134.  
  135.    bzero (re_syntax_table, sizeof re_syntax_table);
  136.  
  137.    for (c = 'a'; c <= 'z'; c++)
  138.      re_syntax_table[c] = Sword;
  139.  
  140.    for (c = 'A'; c <= 'Z'; c++)
  141.      re_syntax_table[c] = Sword;
  142.  
  143.    for (c = '0'; c <= '9'; c++)
  144.      re_syntax_table[c] = Sword;
  145.  
  146.    re_syntax_table['_'] = Sword;
  147.  
  148.    done = 1;
  149. }
  150. #endif /* not SYNTAX_TABLE */
  151. #endif /* not emacs */
  152.  
  153. /* Compile with `-DRX_DEBUG' and use the following flags.
  154.  *
  155.  * Debugging flags:
  156.  *       rx_debug - print information as a regexp is compiled
  157.  *     rx_debug_trace - print information as a regexp is executed
  158.  */
  159.  
  160. #ifdef RX_DEBUG
  161.  
  162. int rx_debug_compile = 0;
  163. int rx_debug_trace = 0;
  164. static struct re_pattern_buffer * dbug_rxb = 0;
  165.  
  166. #ifdef __STDC__
  167. typedef void (*side_effect_printer) (struct rx *, void *, FILE *);
  168. #else
  169. typedef void (*side_effect_printer) ();
  170. #endif
  171.  
  172. #ifdef __STDC__
  173. static void print_cset (struct rx *rx, rx_Bitset cset, FILE * fp);
  174. #else
  175. static void print_cset ();
  176. #endif
  177.  
  178. #ifdef __STDC__
  179. static void
  180. print_rexp (struct rx *rx,
  181.         struct rexp_node *node, int depth,
  182.         side_effect_printer seprint, FILE * fp)
  183. #else
  184. static void
  185. print_rexp (rx, node, depth, seprint, fp)
  186.      struct rx *rx;
  187.      struct rexp_node *node;
  188.      int depth;
  189.      side_effect_printer seprint;
  190.      FILE * fp;
  191. #endif
  192. {
  193.   if (!node)
  194.     return;
  195.   else
  196.     {
  197.       switch (node->type)
  198.     {
  199.     case r_cset:
  200.       {
  201.         fprintf (fp, "%*s", depth, "");
  202.         print_cset (rx, node->params.cset, fp);
  203.         fputc ('\n', fp);
  204.         break;
  205.       }
  206.  
  207.      case r_opt:
  208.     case r_star:
  209.       fprintf (fp, "%*s%s\n", depth, "",
  210.            node->type == r_opt ? "opt" : "star");
  211.       print_rexp (rx, node->params.pair.left, depth + 3, seprint, fp);
  212.       break;
  213.  
  214.     case r_2phase_star:
  215.       fprintf (fp, "%*s2phase star\n", depth, "");
  216.       print_rexp (rx, node->params.pair.right, depth + 3, seprint, fp);
  217.       print_rexp (rx, node->params.pair.left, depth + 3, seprint, fp);
  218.       break;
  219.  
  220.  
  221.     case r_alternate:
  222.     case r_concat:
  223.       fprintf (fp, "%*s%s\n", depth, "",
  224.            node->type == r_alternate ? "alt" : "concat");
  225.       print_rexp (rx, node->params.pair.left, depth + 3, seprint, fp);
  226.       print_rexp (rx, node->params.pair.right, depth + 3, seprint, fp);
  227.       break;
  228.     case r_side_effect:
  229.       fprintf (fp, "%*sSide effect: ", depth, "");
  230.       seprint (rx, node->params.side_effect, fp);
  231.       fputc ('\n', fp);
  232.     }
  233.     }
  234. }
  235.  
  236. #ifdef __STDC__
  237. static void
  238. print_nfa (struct rx * rx,
  239.        struct rx_nfa_state * n,
  240.        side_effect_printer seprint, FILE * fp)
  241. #else
  242. static void
  243. print_nfa (rx, n, seprint, fp)
  244.      struct rx * rx;
  245.      struct rx_nfa_state * n;
  246.      side_effect_printer seprint;
  247.      FILE * fp;
  248. #endif
  249. {
  250.   while (n)
  251.     {
  252.       struct rx_nfa_edge *e = n->edges;
  253.       struct rx_possible_future *ec = n->futures;
  254.       fprintf (fp, "node %d %s\n", n->id,
  255.            n->is_final ? "final" : (n->is_start ? "start" : ""));
  256.       while (e)
  257.     {
  258.       fprintf (fp, "   edge to %d, ", e->dest->id);
  259.       switch (e->type)
  260.         {
  261.         case ne_epsilon:
  262.           fprintf (fp, "epsilon\n");
  263.           break;
  264.         case ne_side_effect:
  265.           fprintf (fp, "side effect ");
  266.           seprint (rx, e->params.side_effect, fp);
  267.           fputc ('\n', fp);
  268.           break;
  269.         case ne_cset:
  270.           fprintf (fp, "cset ");
  271.           print_cset (rx, e->params.cset, fp);
  272.           fputc ('\n', fp);
  273.           break;
  274.         }
  275.       e = e->next;
  276.     }
  277.  
  278.       while (ec)
  279.     {
  280.       int x;
  281.       struct rx_nfa_state_set * s;
  282.       struct rx_se_list * l;
  283.       fprintf (fp, "   eclosure to {");
  284.       for (s = ec->destset; s; s = s->cdr)
  285.         fprintf (fp, "%d ", s->car->id);
  286.       fprintf (fp, "} (");
  287.       for (l = ec->effects; l; l = l->cdr)
  288.         {
  289.           seprint (rx, l->car, fp);
  290.           fputc (' ', fp);
  291.         }
  292.       fprintf (fp, ")\n");
  293.       ec = ec->next;
  294.     }
  295.       n = n->next;
  296.     }
  297. }
  298.  
  299. static char * efnames [] =
  300. {
  301.   "bogon",
  302.   "re_se_try",
  303.   "re_se_pushback",
  304.   "re_se_push0",
  305.   "re_se_pushpos",
  306.   "re_se_chkpos",
  307.   "re_se_poppos",
  308.   "re_se_at_dot",
  309.   "re_se_syntax",
  310.   "re_se_not_syntax",
  311.   "re_se_begbuf",
  312.   "re_se_hat",
  313.   "re_se_wordbeg",
  314.   "re_se_wordbound",
  315.   "re_se_notwordbound",
  316.   "re_se_wordend",
  317.   "re_se_endbuf",
  318.   "re_se_dollar",
  319.   "re_se_fail",
  320. };
  321.  
  322. static char * efnames2[] =
  323. {
  324.   "re_se_win"
  325.   "re_se_lparen",
  326.   "re_se_rparen",
  327.   "re_se_backref",
  328.   "re_se_iter",
  329.   "re_se_end_iter",
  330.   "re_se_tv"
  331. };
  332.  
  333. static char * inx_names[] = 
  334. {
  335.   "rx_backtrack_point",
  336.   "rx_do_side_effects",
  337.   "rx_cache_miss",
  338.   "rx_next_char",
  339.   "rx_backtrack",
  340.   "rx_error_inx",
  341.   "rx_num_instructions"
  342. };
  343.  
  344.  
  345. #ifdef __STDC__
  346. static void
  347. re_seprint (struct rx * rx, void * effect, FILE * fp)
  348. #else
  349. static void
  350. re_seprint (rx, effect, fp)
  351.      struct rx * rx;
  352.      void * effect;
  353.      FILE * fp;
  354. #endif
  355. {
  356.   if ((int)effect < 0)
  357.     fputs (efnames[-(int)effect], fp);
  358.   else if (dbug_rxb)
  359.     {
  360.       struct re_se_params * p = &dbug_rxb->se_params[(int)effect];
  361.       fprintf (fp, "%s(%d,%d)", efnames2[p->se], p->op1, p->op2);
  362.     }
  363.   else
  364.     fprintf (fp, "[complex op # %d]", (int)effect);
  365. }
  366.  
  367.  
  368. /* These are so the regex.c regression tests will compile. */
  369. void
  370. print_compiled_pattern (rxb)
  371.      struct re_pattern_buffer * rxb;
  372. {
  373. }
  374.  
  375. void
  376. print_fastmap (fm)
  377.      char * fm;
  378. {
  379. }
  380.  
  381. #endif /* RX_DEBUG */
  382.  
  383.  
  384.  
  385. /* This page: Bitsets.  Completely unintersting. */
  386.  
  387. #ifdef __STDC__
  388. RX_DECL int
  389. rx_bitset_is_equal (int size, rx_Bitset a, rx_Bitset b)
  390. #else
  391. RX_DECL int
  392. rx_bitset_is_equal (size, a, b)
  393.      int size;
  394.      rx_Bitset a;
  395.      rx_Bitset b;
  396. #endif
  397. {
  398.   int x;
  399.   RX_subset s = b[0];
  400.   b[0] = ~a[0];
  401.  
  402.   for (x = rx_bitset_numb_subsets(size) - 1; a[x] == b[x]; --x)
  403.     ;
  404.  
  405.   b[0] = s;
  406.   return !x && s == a[0];
  407. }
  408.  
  409. #ifdef __STDC__
  410. RX_DECL int
  411. rx_bitset_is_subset (int size, rx_Bitset a, rx_Bitset b)
  412. #else
  413. RX_DECL int
  414. rx_bitset_is_subset (size, a, b)
  415.      int size;
  416.      rx_Bitset a;
  417.      rx_Bitset b;
  418. #endif
  419. {
  420.   int x = rx_bitset_numb_subsets(size) - 1;
  421.   while (x-- && (a[x] & b[x]) == a[x]);
  422.   return x == -1;
  423. }
  424.  
  425.  
  426. #ifdef __STDC__
  427. RX_DECL int
  428. rx_bitset_empty (int size, rx_Bitset set)
  429. #else
  430. RX_DECL int
  431. rx_bitset_empty (size, set)
  432.      int size;
  433.      rx_Bitset set;
  434. #endif
  435. {
  436.   int x;
  437.   RX_subset s = set[0];
  438.   set[0] = 1;
  439.   for (x = rx_bitset_numb_subsets(size) - 1; !set[x]; --x)
  440.     ;
  441.   set[0] = s;
  442.   return !s;
  443. }
  444.  
  445. #ifdef __STDC__
  446. RX_DECL void
  447. rx_bitset_null (int size, rx_Bitset b)
  448. #else
  449. RX_DECL void
  450. rx_bitset_null (size, b)
  451.      int size;
  452.      rx_Bitset b;
  453. #endif
  454. {
  455.   bzero (b, rx_sizeof_bitset(size));
  456. }
  457.  
  458.  
  459. #ifdef __STDC__
  460. RX_DECL void
  461. rx_bitset_universe (int size, rx_Bitset b)
  462. #else
  463. RX_DECL void
  464. rx_bitset_universe (size, b)
  465.      int size;
  466.      rx_Bitset b;
  467. #endif
  468. {
  469.   int x = rx_bitset_numb_subsets (size);
  470.   while (x--)
  471.     *b++ = ~(RX_subset)0;
  472. }
  473.  
  474.  
  475. #ifdef __STDC__
  476. RX_DECL void
  477. rx_bitset_complement (int size, rx_Bitset b)
  478. #else
  479. RX_DECL void
  480. rx_bitset_complement (size, b)
  481.      int size;
  482.      rx_Bitset b;
  483. #endif
  484. {
  485.   int x = rx_bitset_numb_subsets (size);
  486.   while (x--)
  487.     {
  488.       *b = ~*b;
  489.       ++b;
  490.     }
  491. }
  492.  
  493.  
  494. #ifdef __STDC__
  495. RX_DECL void
  496. rx_bitset_assign (int size, rx_Bitset a, rx_Bitset b)
  497. #else
  498. RX_DECL void
  499. rx_bitset_assign (size, a, b)
  500.      int size;
  501.      rx_Bitset a;
  502.      rx_Bitset b;
  503. #endif
  504. {
  505.   int x;
  506.   for (x = rx_bitset_numb_subsets(size) - 1; x >=0; --x)
  507.     a[x] = b[x];
  508. }
  509.  
  510.  
  511. #ifdef __STDC__
  512. RX_DECL void
  513. rx_bitset_union (int size, rx_Bitset a, rx_Bitset b)
  514. #else
  515. RX_DECL void
  516. rx_bitset_union (size, a, b)
  517.      int size;
  518.      rx_Bitset a;
  519.      rx_Bitset b;
  520. #endif
  521. {
  522.   int x;
  523.   for (x = rx_bitset_numb_subsets(size) - 1; x >=0; --x)
  524.     a[x] |= b[x];
  525. }
  526.  
  527.  
  528. #ifdef __STDC__
  529. RX_DECL void
  530. rx_bitset_intersection (int size,
  531.             rx_Bitset a, rx_Bitset b)
  532. #else
  533. RX_DECL void
  534. rx_bitset_intersection (size, a, b)
  535.      int size;
  536.      rx_Bitset a;
  537.      rx_Bitset b;
  538. #endif
  539. {
  540.   int x;
  541.   for (x = rx_bitset_numb_subsets(size) - 1; x >=0; --x)
  542.     a[x] &= b[x];
  543. }
  544.  
  545.  
  546. #ifdef __STDC__
  547. RX_DECL void
  548. rx_bitset_difference (int size, rx_Bitset a, rx_Bitset b)
  549. #else
  550. RX_DECL void
  551. rx_bitset_difference (size, a, b)
  552.      int size;
  553.      rx_Bitset a;
  554.      rx_Bitset b;
  555. #endif
  556. {
  557.   int x;
  558.   for (x = rx_bitset_numb_subsets(size) - 1; x >=0; --x)
  559.     a[x] &=  ~ b[x];
  560. }
  561.  
  562.  
  563. #ifdef __STDC__
  564. RX_DECL void
  565. rx_bitset_revdifference (int size,
  566.              rx_Bitset a, rx_Bitset b)
  567. #else
  568. RX_DECL void
  569. rx_bitset_revdifference (size, a, b)
  570.      int size;
  571.      rx_Bitset a;
  572.      rx_Bitset b;
  573. #endif
  574. {
  575.   int x;
  576.   for (x = rx_bitset_numb_subsets(size) - 1; x >=0; --x)
  577.     a[x] = ~a[x] & b[x];
  578. }
  579.  
  580. #ifdef __STDC__
  581. RX_DECL void
  582. rx_bitset_xor (int size, rx_Bitset a, rx_Bitset b)
  583. #else
  584. RX_DECL void
  585. rx_bitset_xor (size, a, b)
  586.      int size;
  587.      rx_Bitset a;
  588.      rx_Bitset b;
  589. #endif
  590. {
  591.   int x;
  592.   for (x = rx_bitset_numb_subsets(size) - 1; x >=0; --x)
  593.     a[x] ^= b[x];
  594. }
  595.  
  596.  
  597. #ifdef __STDC__
  598. RX_DECL unsigned long
  599. rx_bitset_hash (int size, rx_Bitset b)
  600. #else
  601. RX_DECL unsigned long
  602. rx_bitset_hash (size, b)
  603.      int size;
  604.      rx_Bitset b;
  605. #endif
  606. {
  607.   int x;
  608.   unsigned long hash = (unsigned long)rx_bitset_hash;
  609.  
  610.   for (x = rx_bitset_numb_subsets(size) - 1; x >= 0; --x)
  611.     hash ^= rx_bitset_subset_val(b, x);
  612.  
  613.   return hash;
  614. }
  615.  
  616.  
  617. RX_DECL RX_subset rx_subset_singletons [RX_subset_bits] = 
  618. {
  619.   0x1,
  620.   0x2,
  621.   0x4,
  622.   0x8,
  623.   0x10,
  624.   0x20,
  625.   0x40,
  626.   0x80,
  627.   0x100,
  628.   0x200,
  629.   0x400,
  630.   0x800,
  631.   0x1000,
  632.   0x2000,
  633.   0x4000,
  634.   0x8000,
  635.   0x10000,
  636.   0x20000,
  637.   0x40000,
  638.   0x80000,
  639.   0x100000,
  640.   0x200000,
  641.   0x400000,
  642.   0x800000,
  643.   0x1000000,
  644.   0x2000000,
  645.   0x4000000,
  646.   0x8000000,
  647.   0x10000000,
  648.   0x20000000,
  649.   0x40000000,
  650.   0x80000000
  651. };
  652.  
  653. #ifdef RX_DEBUG
  654.  
  655. #ifdef __STDC__
  656. static void
  657. print_cset (struct rx *rx, rx_Bitset cset, FILE * fp)
  658. #else
  659. static void
  660. print_cset (rx, cset, fp)
  661.      struct rx *rx;
  662.      rx_Bitset cset;
  663.      FILE * fp;
  664. #endif
  665. {
  666.   int x;
  667.   fputc ('[', fp);
  668.   for (x = 0; x < rx->local_cset_size; ++x)
  669.     if (isprint(x) && RX_bitset_member (cset, x))
  670.       fputc (x, fp);
  671.   fputc (']', fp);
  672. }
  673.  
  674. #endif /*  RX_DEBUG */
  675.  
  676.  
  677.  
  678. static unsigned long rx_hash_masks[4] =
  679. {
  680.   0x12488421,
  681.   0x96699669,
  682.   0xbe7dd7eb,
  683.   0xffffffff
  684. };
  685.  
  686.  
  687. /* Hash tables */
  688. #ifdef __STDC__
  689. RX_DECL struct rx_hash_item * 
  690. rx_hash_find (struct rx_hash * table,
  691.           unsigned long hash,
  692.           void * value,
  693.           struct rx_hash_rules * rules)
  694. #else
  695. RX_DECL struct rx_hash_item * 
  696. rx_hash_find (table, hash, value, rules)
  697.      struct rx_hash * table;
  698.      unsigned long hash;
  699.      void * value;
  700.      struct rx_hash_rules * rules;
  701. #endif
  702. {
  703.   rx_hash_eq eq = rules->eq;
  704.   int maskc = 0;
  705.   long mask = rx_hash_masks [0];
  706.   int bucket = (hash & mask) % 13;
  707.  
  708.   while (table->children [bucket])
  709.     {
  710.       table = table->children [bucket];
  711.       ++maskc;
  712.       mask = rx_hash_masks[maskc];
  713.       bucket = (hash & mask) % 13;
  714.     }
  715.  
  716.   {
  717.     struct rx_hash_item * it = table->buckets[bucket];
  718.     while (it)
  719.       if (eq (it->data, value))
  720.     return it;
  721.       else
  722.     it = it->next_same_hash;
  723.   }
  724.  
  725.   return 0;
  726. }
  727.  
  728.  
  729. #ifdef __STDC__
  730. RX_DECL struct rx_hash_item *
  731. rx_hash_store (struct rx_hash * table,
  732.            unsigned long hash,
  733.            void * value,
  734.            struct rx_hash_rules * rules)
  735. #else
  736. RX_DECL struct rx_hash_item *
  737. rx_hash_store (table, hash, value, rules)
  738.      struct rx_hash * table;
  739.      unsigned long hash;
  740.      void * value;
  741.      struct rx_hash_rules * rules;
  742. #endif
  743. {
  744.   rx_hash_eq eq = rules->eq;
  745.   int maskc = 0;
  746.   long mask = rx_hash_masks[0];
  747.   int bucket = (hash & mask) % 13;
  748.   int depth = 0;
  749.   
  750.   while (table->children [bucket])
  751.     {
  752.       table = table->children [bucket];
  753.       ++maskc;
  754.       mask = rx_hash_masks[maskc];
  755.       bucket = (hash & mask) % 13;
  756.       ++depth;
  757.     }
  758.   
  759.   {
  760.     struct rx_hash_item * it = table->buckets[bucket];
  761.     while (it)
  762.       if (eq (it->data, value))
  763.     return it;
  764.       else
  765.     it = it->next_same_hash;
  766.   }
  767.   
  768.   {
  769.     if (   (depth < 3)
  770.     && (table->bucket_size [bucket] >= 4))
  771.       {
  772.     struct rx_hash * newtab = ((struct rx_hash *)
  773.                    rules->hash_alloc (rules));
  774.     if (!newtab)
  775.       goto add_to_bucket;
  776.     bzero (newtab, sizeof (*newtab));
  777.     newtab->parent = table;
  778.     {
  779.       struct rx_hash_item * them = table->buckets[bucket];
  780.       unsigned long newmask = rx_hash_masks[maskc + 1];
  781.       while (them)
  782.         {
  783.           struct rx_hash_item * save = them->next_same_hash;
  784.           int new_buck = (them->hash & newmask) % 13;
  785.           them->next_same_hash = newtab->buckets[new_buck];
  786.           newtab->buckets[new_buck] = them;
  787.           them->table = newtab;
  788.           them = save;
  789.           ++newtab->bucket_size[new_buck];
  790.           ++newtab->refs;
  791.         }
  792.       table->refs = (table->refs - table->bucket_size[bucket] + 1);
  793.       table->bucket_size[bucket] = 0;
  794.       table->buckets[bucket] = 0;
  795.       table->children[bucket] = newtab;
  796.       table = newtab;
  797.       bucket = (hash & newmask) % 13;
  798.     }
  799.       }
  800.   }
  801.  add_to_bucket:
  802.   {
  803.     struct rx_hash_item  * it = ((struct rx_hash_item *)
  804.                  rules->hash_item_alloc (rules, value));
  805.     if (!it)
  806.       return 0;
  807.     it->hash = hash;
  808.     it->table = table;
  809.     /* DATA and BINDING are to be set in hash_item_alloc */
  810.     it->next_same_hash = table->buckets [bucket];
  811.     table->buckets[bucket] = it;
  812.     ++table->bucket_size [bucket];
  813.     ++table->refs;
  814.     return it;
  815.   }
  816. }
  817.  
  818.  
  819. #ifdef __STDC__
  820. RX_DECL void
  821. rx_hash_free (struct rx_hash_item * it, struct rx_hash_rules * rules)
  822. #else
  823. RX_DECL void
  824. rx_hash_free (it, rules)
  825.      struct rx_hash_item * it;
  826.      struct rx_hash_rules * rules;
  827. #endif
  828. {
  829.   if (it)
  830.     {
  831.       struct rx_hash * table = it->table;
  832.       unsigned long hash = it->hash;
  833.       int depth = (table->parent
  834.            ? (table->parent->parent
  835.               ? (table->parent->parent->parent
  836.              ? 3
  837.              : 2)
  838.               : 1)
  839.            : 0);
  840.       int bucket = (hash & rx_hash_masks [depth]) % 13;
  841.       struct rx_hash_item ** pos = &table->buckets [bucket];
  842.       
  843.       while (*pos != it)
  844.     pos = &(*pos)->next_same_hash;
  845.       *pos = it->next_same_hash;
  846.       rules->free_hash_item (it, rules);
  847.       --table->bucket_size[bucket];
  848.       --table->refs;
  849.       while (!table->refs && depth)
  850.     {
  851.       struct rx_hash * save = table;
  852.       table = table->parent;
  853.       --depth;
  854.       bucket = (hash & rx_hash_masks [depth]) % 13;
  855.       --table->refs;
  856.       table->children[bucket] = 0;
  857.       rules->free_hash (save, rules);
  858.     }
  859.     }
  860. }
  861.  
  862. #ifdef __STDC__
  863. RX_DECL void
  864. rx_free_hash_table (struct rx_hash * tab, rx_hash_freefn freefn,
  865.             struct rx_hash_rules * rules)
  866. #else
  867. RX_DECL void
  868. rx_free_hash_table (tab, freefn, rules)
  869.      struct rx_hash * tab;
  870.      rx_hash_freefn freefn;
  871.      struct rx_hash_rules * rules;
  872. #endif
  873. {
  874.   int x;
  875.  
  876.   for (x = 0; x < 13; ++x)
  877.     if (tab->children[x])
  878.       {
  879.     rx_free_hash_table (tab->children[x], freefn, rules);
  880.     rules->free_hash (tab->children[x], rules);
  881.       }
  882.     else
  883.       {
  884.     struct rx_hash_item * them = tab->buckets[x];
  885.     while (them)
  886.       {
  887.         struct rx_hash_item * that = them;
  888.         them = that->next_same_hash;
  889.         freefn (that);
  890.         rules->free_hash_item (that, rules);
  891.       }
  892.       }
  893. }
  894.  
  895.  
  896.  
  897. /* Utilities for manipulating bitset represntations of characters sets. */
  898.  
  899. #ifdef __STDC__
  900. RX_DECL rx_Bitset
  901. rx_cset (struct rx *rx)
  902. #else
  903. RX_DECL rx_Bitset
  904. rx_cset (rx)
  905.      struct rx *rx;
  906. #endif
  907. {
  908.   rx_Bitset b = (rx_Bitset) malloc (rx_sizeof_bitset (rx->local_cset_size));
  909.   if (b)
  910.     rx_bitset_null (rx->local_cset_size, b);
  911.   return b;
  912. }
  913.  
  914.  
  915. #ifdef __STDC__
  916. RX_DECL rx_Bitset
  917. rx_copy_cset (struct rx *rx, rx_Bitset a)
  918. #else
  919. RX_DECL rx_Bitset
  920. rx_copy_cset (rx, a)
  921.      struct rx *rx;
  922.      rx_Bitset a;
  923. #endif
  924. {
  925.   rx_Bitset cs = rx_cset (rx);
  926.  
  927.   if (cs)
  928.     rx_bitset_union (rx->local_cset_size, cs, a);
  929.  
  930.   return cs;
  931. }
  932.  
  933.  
  934. #ifdef __STDC__
  935. RX_DECL void
  936. rx_free_cset (struct rx * rx, rx_Bitset c)
  937. #else
  938. RX_DECL void
  939. rx_free_cset (rx, c)
  940.      struct rx * rx;
  941.      rx_Bitset c;
  942. #endif
  943. {
  944.   if (c)
  945.     free ((char *)c);
  946. }
  947.  
  948.  
  949. /* Hash table memory allocation policy for the regexp compiler */
  950.  
  951. #ifdef __STDC__
  952. static struct rx_hash *
  953. compiler_hash_alloc (struct rx_hash_rules * rules)
  954. #else
  955. static struct rx_hash *
  956. compiler_hash_alloc (rules)
  957.      struct rx_hash_rules * rules;
  958. #endif
  959. {
  960.   return (struct rx_hash *)malloc (sizeof (struct rx_hash));
  961. }
  962.  
  963.  
  964. #ifdef __STDC__
  965. static struct rx_hash_item *
  966. compiler_hash_item_alloc (struct rx_hash_rules * rules, void * value)
  967. #else
  968. static struct rx_hash_item *
  969. compiler_hash_item_alloc (rules, value)
  970.      struct rx_hash_rules * rules;
  971.      void * value;
  972. #endif
  973. {
  974.   struct rx_hash_item * it;
  975.   it = (struct rx_hash_item *)malloc (sizeof (*it));
  976.   if (it)
  977.     {
  978.       it->data = value;
  979.       it->binding = 0;
  980.     }
  981.   return it;
  982. }
  983.  
  984.  
  985. #ifdef __STDC__
  986. static void
  987. compiler_free_hash (struct rx_hash * tab,
  988.             struct rx_hash_rules * rules)
  989. #else
  990. static void
  991. compiler_free_hash (tab, rules)
  992.      struct rx_hash * tab;
  993.      struct rx_hash_rules * rules;
  994. #endif
  995. {
  996.   free ((char *)tab);
  997. }
  998.  
  999.  
  1000. #ifdef __STDC__
  1001. static void
  1002. compiler_free_hash_item (struct rx_hash_item * item,
  1003.              struct rx_hash_rules * rules)
  1004. #else
  1005. static void
  1006. compiler_free_hash_item (item, rules)
  1007.      struct rx_hash_item * item;
  1008.      struct rx_hash_rules * rules;
  1009. #endif
  1010. {
  1011.   free ((char *)item);
  1012. }
  1013.  
  1014.  
  1015. /* This page: REXP_NODE (expression tree) structures. */
  1016.  
  1017. #ifdef __STDC__
  1018. RX_DECL struct rexp_node *
  1019. rexp_node (struct rx *rx,
  1020.        enum rexp_node_type type)
  1021. #else
  1022. RX_DECL struct rexp_node *
  1023. rexp_node (rx, type)
  1024.      struct rx *rx;
  1025.      enum rexp_node_type type;
  1026. #endif
  1027. {
  1028.   struct rexp_node *n;
  1029.  
  1030.   n = (struct rexp_node *)malloc (sizeof (*n));
  1031.   bzero (n, sizeof (*n));
  1032.   if (n)
  1033.     n->type = type;
  1034.   return n;
  1035. }
  1036.  
  1037.  
  1038. /* free_rexp_node assumes that the bitset passed to rx_mk_r_cset
  1039.  * can be freed using rx_free_cset.
  1040.  */
  1041. #ifdef __STDC__
  1042. RX_DECL struct rexp_node *
  1043. rx_mk_r_cset (struct rx * rx,
  1044.           rx_Bitset b)
  1045. #else
  1046. RX_DECL struct rexp_node *
  1047. rx_mk_r_cset (rx, b)
  1048.      struct rx * rx;
  1049.      rx_Bitset b;
  1050. #endif
  1051. {
  1052.   struct rexp_node * n = rexp_node (rx, r_cset);
  1053.   if (n)
  1054.     n->params.cset = b;
  1055.   return n;
  1056. }
  1057.  
  1058.  
  1059. #ifdef __STDC__
  1060. RX_DECL struct rexp_node *
  1061. rx_mk_r_concat (struct rx * rx,
  1062.         struct rexp_node * a,
  1063.         struct rexp_node * b)
  1064. #else
  1065. RX_DECL struct rexp_node *
  1066. rx_mk_r_concat (rx, a, b)
  1067.      struct rx * rx;
  1068.      struct rexp_node * a;
  1069.      struct rexp_node * b;
  1070. #endif
  1071. {
  1072.   struct rexp_node * n = rexp_node (rx, r_concat);
  1073.   if (n)
  1074.     {
  1075.       n->params.pair.left = a;
  1076.       n->params.pair.right = b;
  1077.     }
  1078.   return n;
  1079. }
  1080.  
  1081.  
  1082. #ifdef __STDC__
  1083. RX_DECL struct rexp_node *
  1084. rx_mk_r_alternate (struct rx * rx,
  1085.            struct rexp_node * a,
  1086.            struct rexp_node * b)
  1087. #else
  1088. RX_DECL struct rexp_node *
  1089. rx_mk_r_alternate (rx, a, b)
  1090.      struct rx * rx;
  1091.      struct rexp_node * a;
  1092.      struct rexp_node * b;
  1093. #endif
  1094. {
  1095.   struct rexp_node * n = rexp_node (rx, r_alternate);
  1096.   if (n)
  1097.     {
  1098.       n->params.pair.left = a;
  1099.       n->params.pair.right = b;
  1100.     }
  1101.   return n;
  1102. }
  1103.  
  1104.  
  1105. #ifdef __STDC__
  1106. RX_DECL struct rexp_node *
  1107. rx_mk_r_opt (struct rx * rx,
  1108.          struct rexp_node * a)
  1109. #else
  1110. RX_DECL struct rexp_node *
  1111. rx_mk_r_opt (rx, a)
  1112.      struct rx * rx;
  1113.      struct rexp_node * a;
  1114. #endif
  1115. {
  1116.   struct rexp_node * n = rexp_node (rx, r_opt);
  1117.   if (n)
  1118.     {
  1119.       n->params.pair.left = a;
  1120.       n->params.pair.right = 0;
  1121.     }
  1122.   return n;
  1123. }
  1124.  
  1125.  
  1126. #ifdef __STDC__
  1127. RX_DECL struct rexp_node *
  1128. rx_mk_r_star (struct rx * rx,
  1129.           struct rexp_node * a)
  1130. #else
  1131. RX_DECL struct rexp_node *
  1132. rx_mk_r_star (rx, a)
  1133.      struct rx * rx;
  1134.      struct rexp_node * a;
  1135. #endif
  1136. {
  1137.   struct rexp_node * n = rexp_node (rx, r_star);
  1138.   if (n)
  1139.     {
  1140.       n->params.pair.left = a;
  1141.       n->params.pair.right = 0;
  1142.     }
  1143.   return n;
  1144. }
  1145.  
  1146.  
  1147. #ifdef __STDC__
  1148. RX_DECL struct rexp_node *
  1149. rx_mk_r_2phase_star (struct rx * rx,
  1150.              struct rexp_node * a,
  1151.              struct rexp_node * b)
  1152. #else
  1153. RX_DECL struct rexp_node *
  1154. rx_mk_r_2phase_star (rx, a, b)
  1155.      struct rx * rx;
  1156.      struct rexp_node * a;
  1157.      struct rexp_node * b;
  1158. #endif
  1159. {
  1160.   struct rexp_node * n = rexp_node (rx, r_2phase_star);
  1161.   if (n)
  1162.     {
  1163.       n->params.pair.left = a;
  1164.       n->params.pair.right = b;
  1165.     }
  1166.   return n;
  1167. }
  1168.  
  1169.  
  1170. #ifdef __STDC__
  1171. RX_DECL struct rexp_node *
  1172. rx_mk_r_side_effect (struct rx * rx,
  1173.              rx_side_effect a)
  1174. #else
  1175. RX_DECL struct rexp_node *
  1176. rx_mk_r_side_effect (rx, a)
  1177.      struct rx * rx;
  1178.      rx_side_effect a;
  1179. #endif
  1180. {
  1181.   struct rexp_node * n = rexp_node (rx, r_side_effect);
  1182.   if (n)
  1183.     {
  1184.       n->params.side_effect = a;
  1185.       n->params.pair.right = 0;
  1186.     }
  1187.   return n;
  1188. }
  1189.  
  1190.  
  1191. #ifdef __STDC__
  1192. RX_DECL struct rexp_node *
  1193. rx_mk_r_data  (struct rx * rx,
  1194.            void * a)
  1195. #else
  1196. RX_DECL struct rexp_node *
  1197. rx_mk_r_data  (rx, a)
  1198.      struct rx * rx;
  1199.      void * a;
  1200. #endif
  1201. {
  1202.   struct rexp_node * n = rexp_node (rx, r_data);
  1203.   if (n)
  1204.     {
  1205.       n->params.pair.left = a;
  1206.       n->params.pair.right = 0;
  1207.     }
  1208.   return n;
  1209. }
  1210.  
  1211.  
  1212. #ifdef __STDC__
  1213. RX_DECL void
  1214. rx_free_rexp (struct rx * rx, struct rexp_node * node)
  1215. #else
  1216. RX_DECL void
  1217. rx_free_rexp (rx, node)
  1218.      struct rx * rx;
  1219.      struct rexp_node * node;
  1220. #endif
  1221. {
  1222.   if (node)
  1223.     {
  1224.       switch (node->type)
  1225.     {
  1226.     case r_cset:
  1227.       if (node->params.cset)
  1228.         rx_free_cset (rx, node->params.cset);
  1229.  
  1230.     case r_side_effect:
  1231.       break;
  1232.       
  1233.     case r_concat:
  1234.     case r_alternate:
  1235.     case r_2phase_star:
  1236.     case r_opt:
  1237.     case r_star:
  1238.       rx_free_rexp (rx, node->params.pair.left);
  1239.       rx_free_rexp (rx, node->params.pair.right);
  1240.       break;
  1241.  
  1242.     case r_data:
  1243.       /* This shouldn't occur. */
  1244.       break;
  1245.     }
  1246.       free ((char *)node);
  1247.     }
  1248. }
  1249.  
  1250.  
  1251. #ifdef __STDC__
  1252. RX_DECL struct rexp_node * 
  1253. rx_copy_rexp (struct rx *rx,
  1254.        struct rexp_node *node)
  1255. #else
  1256. RX_DECL struct rexp_node * 
  1257. rx_copy_rexp (rx, node)
  1258.      struct rx *rx;
  1259.      struct rexp_node *node;
  1260. #endif
  1261. {
  1262.   if (!node)
  1263.     return 0;
  1264.   else
  1265.     {
  1266.       struct rexp_node *n = rexp_node (rx, node->type);
  1267.       if (!n)
  1268.     return 0;
  1269.       switch (node->type)
  1270.     {
  1271.     case r_cset:
  1272.       n->params.cset = rx_copy_cset (rx, node->params.cset);
  1273.       if (!n->params.cset)
  1274.         {
  1275.           rx_free_rexp (rx, n);
  1276.           return 0;
  1277.         }
  1278.       break;
  1279.  
  1280.     case r_side_effect:
  1281.       n->params.side_effect = node->params.side_effect;
  1282.       break;
  1283.  
  1284.     case r_concat:
  1285.     case r_alternate:
  1286.     case r_opt:
  1287.     case r_2phase_star:
  1288.     case r_star:
  1289.       n->params.pair.left =
  1290.         rx_copy_rexp (rx, node->params.pair.left);
  1291.       n->params.pair.right =
  1292.         rx_copy_rexp (rx, node->params.pair.right);
  1293.       if (   (node->params.pair.left && !n->params.pair.left)
  1294.           || (node->params.pair.right && !n->params.pair.right))
  1295.         {
  1296.           rx_free_rexp  (rx, n);
  1297.           return 0;
  1298.         }
  1299.       break;
  1300.     case r_data:
  1301.       /* shouldn't happen */
  1302.       break;
  1303.     }
  1304.       return n;
  1305.     }
  1306. }
  1307.  
  1308.  
  1309.  
  1310. /* This page: functions to build and destroy graphs that describe nfa's */
  1311.  
  1312. /* Constructs a new nfa node. */
  1313. #ifdef __STDC__
  1314. RX_DECL struct rx_nfa_state *
  1315. rx_nfa_state (struct rx *rx)
  1316. #else
  1317. RX_DECL struct rx_nfa_state *
  1318. rx_nfa_state (rx)
  1319.      struct rx *rx;
  1320. #endif
  1321. {
  1322.   struct rx_nfa_state * n = (struct rx_nfa_state *)malloc (sizeof (*n));
  1323.   if (!n)
  1324.     return 0;
  1325.   bzero (n, sizeof (*n));
  1326.   n->next = rx->nfa_states;
  1327.   rx->nfa_states = n;
  1328.   return n;
  1329. }
  1330.  
  1331.  
  1332. #ifdef __STDC__
  1333. RX_DECL void
  1334. rx_free_nfa_state (struct rx_nfa_state * n)
  1335. #else
  1336. RX_DECL void
  1337. rx_free_nfa_state (n)
  1338.   struct rx_nfa_state * n;
  1339. #endif
  1340. {
  1341.   free ((char *)n);
  1342. }
  1343.  
  1344.  
  1345. /* This looks up an nfa node, given a numeric id.  Numeric id's are
  1346.  * assigned after the nfa has been built.
  1347.  */
  1348. #ifdef __STDC__
  1349. RX_DECL struct rx_nfa_state * 
  1350. rx_id_to_nfa_state (struct rx * rx,
  1351.             int id)
  1352. #else
  1353. RX_DECL struct rx_nfa_state * 
  1354. rx_id_to_nfa_state (rx, id)
  1355.      struct rx * rx;
  1356.      int id;
  1357. #endif
  1358. {
  1359.   struct rx_nfa_state * n;
  1360.   for (n = rx->nfa_states; n; n = n->next)
  1361.     if (n->id == id)
  1362.       return n;
  1363.   return 0;
  1364. }
  1365.  
  1366.  
  1367. /* This adds an edge between two nodes, but doesn't initialize the 
  1368.  * edge label.
  1369.  */
  1370.  
  1371. #ifdef __STDC__
  1372. RX_DECL struct rx_nfa_edge * 
  1373. rx_nfa_edge (struct rx *rx,
  1374.          enum rx_nfa_etype type,
  1375.          struct rx_nfa_state *start,
  1376.          struct rx_nfa_state *dest)
  1377. #else
  1378. RX_DECL struct rx_nfa_edge * 
  1379. rx_nfa_edge (rx, type, start, dest)
  1380.      struct rx *rx;
  1381.      enum rx_nfa_etype type;
  1382.      struct rx_nfa_state *start;
  1383.      struct rx_nfa_state *dest;
  1384. #endif
  1385. {
  1386.   struct rx_nfa_edge *e;
  1387.   e = (struct rx_nfa_edge *)malloc (sizeof (*e));
  1388.   if (!e)
  1389.     return 0;
  1390.   e->next = start->edges;
  1391.   start->edges = e;
  1392.   e->type = type;
  1393.   e->dest = dest;
  1394.   return e;
  1395. }
  1396.  
  1397.  
  1398. #ifdef __STDC__
  1399. RX_DECL void
  1400. rx_free_nfa_edge (struct rx_nfa_edge * e)
  1401. #else
  1402. RX_DECL void
  1403. rx_free_nfa_edge (e)
  1404.      struct rx_nfa_edge * e;
  1405. #endif
  1406. {
  1407.   free ((char *)e);
  1408. }
  1409.  
  1410.  
  1411. /* This constructs a POSSIBLE_FUTURE, which is a kind epsilon-closure
  1412.  * of an NFA.  These are added to an nfa automaticly by eclose_nfa.
  1413.  */  
  1414.  
  1415. #ifdef __STDC__
  1416. static struct rx_possible_future * 
  1417. rx_possible_future (struct rx * rx,
  1418.          struct rx_se_list * effects)
  1419. #else
  1420. static struct rx_possible_future * 
  1421. rx_possible_future (rx, effects)
  1422.      struct rx * rx;
  1423.      struct rx_se_list * effects;
  1424. #endif
  1425. {
  1426.   struct rx_possible_future *ec;
  1427.   ec = (struct rx_possible_future *) malloc (sizeof (*ec));
  1428.   if (!ec)
  1429.     return 0;
  1430.   ec->destset = 0;
  1431.   ec->next = 0;
  1432.   ec->effects = effects;
  1433.   return ec;
  1434. }
  1435.  
  1436.  
  1437. #ifdef __STDC__
  1438. static void
  1439. rx_free_possible_future (struct rx_possible_future * pf)
  1440. #else
  1441. static void
  1442. rx_free_possible_future (pf)
  1443.      struct rx_possible_future * pf;
  1444. #endif
  1445. {
  1446.   free ((char *)pf);
  1447. }
  1448.  
  1449.  
  1450. #ifdef __STDC__
  1451. RX_DECL void
  1452. rx_free_nfa (struct rx *rx)
  1453. #else
  1454. RX_DECL void
  1455. rx_free_nfa (rx)
  1456.      struct rx *rx;
  1457. #endif
  1458. {
  1459.   while (rx->nfa_states)
  1460.     {
  1461.       while (rx->nfa_states->edges)
  1462.     {
  1463.       switch (rx->nfa_states->edges->type)
  1464.         {
  1465.         case ne_cset:
  1466.           rx_free_cset (rx, rx->nfa_states->edges->params.cset);
  1467.           break;
  1468.         default:
  1469.           break;
  1470.         }
  1471.       {
  1472.         struct rx_nfa_edge * e;
  1473.         e = rx->nfa_states->edges;
  1474.         rx->nfa_states->edges = rx->nfa_states->edges->next;
  1475.         rx_free_nfa_edge (e);
  1476.       }
  1477.     } /* while (rx->nfa_states->edges) */
  1478.       {
  1479.     /* Iterate over the partial epsilon closures of rx->nfa_states */
  1480.     struct rx_possible_future * pf = rx->nfa_states->futures;
  1481.     while (pf)
  1482.       {
  1483.         struct rx_possible_future * pft = pf;
  1484.         pf = pf->next;
  1485.         rx_free_possible_future (pft);
  1486.       }
  1487.       }
  1488.       {
  1489.     struct rx_nfa_state *n;
  1490.     n = rx->nfa_states;
  1491.     rx->nfa_states = rx->nfa_states->next;
  1492.     rx_free_nfa_state (n);
  1493.       }
  1494.     }
  1495. }
  1496.  
  1497.  
  1498.  
  1499. /* This page: translating a pattern expression into an nfa and doing the 
  1500.  * static part of the nfa->super-nfa translation.
  1501.  */
  1502.  
  1503. /* This is the thompson regexp->nfa algorithm. 
  1504.  * It is modified to allow for `side-effect epsilons.'  Those are
  1505.  * edges that are taken whenever a similar epsilon edge would be,
  1506.  * but which imply that some side effect occurs when the edge 
  1507.  * is taken.
  1508.  *
  1509.  * Side effects are used to model parts of the pattern langauge 
  1510.  * that are not regular (in the formal sense).
  1511.  */
  1512.  
  1513. #ifdef __STDC__
  1514. RX_DECL int
  1515. rx_build_nfa (struct rx *rx,
  1516.           struct rexp_node *rexp,
  1517.           struct rx_nfa_state **start,
  1518.           struct rx_nfa_state **end)
  1519. #else
  1520. RX_DECL int
  1521. rx_build_nfa (rx, rexp, start, end)
  1522.      struct rx *rx;
  1523.      struct rexp_node *rexp;
  1524.      struct rx_nfa_state **start;
  1525.      struct rx_nfa_state **end;
  1526. #endif
  1527. {
  1528.   struct rx_nfa_edge *edge;
  1529.  
  1530.   /* Start & end nodes may have been allocated by the caller. */
  1531.   *start = *start ? *start : rx_nfa_state (rx);
  1532.  
  1533.   if (!*start)
  1534.     return 0;
  1535.  
  1536.   if (!rexp)
  1537.     {
  1538.       *end = *start;
  1539.       return 1;
  1540.     }
  1541.  
  1542.   *end = *end ? *end : rx_nfa_state (rx);
  1543.  
  1544.   if (!*end)
  1545.     {
  1546.       rx_free_nfa_state (*start);
  1547.       return 0;
  1548.     }
  1549.  
  1550.   switch (rexp->type)
  1551.     {
  1552.     case r_data:
  1553.       return 0;
  1554.  
  1555.     case r_cset:
  1556.       edge = rx_nfa_edge (rx, ne_cset, *start, *end);
  1557.       if (!edge)
  1558.     return 0;
  1559.       edge->params.cset = rx_copy_cset (rx, rexp->params.cset);
  1560.       if (!edge->params.cset)
  1561.     {
  1562.       rx_free_nfa_edge (edge);
  1563.       return 0;
  1564.     }
  1565.       return 1;
  1566.  
  1567.     case r_opt:
  1568.       return (rx_build_nfa (rx, rexp->params.pair.left, start, end)
  1569.           && rx_nfa_edge (rx, ne_epsilon, *start, *end));
  1570.  
  1571.     case r_star:
  1572.       {
  1573.     struct rx_nfa_state * star_start = 0;
  1574.     struct rx_nfa_state * star_end = 0;
  1575.     return (rx_build_nfa (rx, rexp->params.pair.left,
  1576.                   &star_start, &star_end)
  1577.         && star_start
  1578.         && star_end
  1579.         && rx_nfa_edge (rx, ne_epsilon, star_start, star_end)
  1580.         && rx_nfa_edge (rx, ne_epsilon, *start, star_start)
  1581.         && rx_nfa_edge (rx, ne_epsilon, star_end, *end)
  1582.  
  1583.         && rx_nfa_edge (rx, ne_epsilon, star_end, star_start));
  1584.       }
  1585.  
  1586.     case r_2phase_star:
  1587.       {
  1588.     struct rx_nfa_state * star_start = 0;
  1589.     struct rx_nfa_state * star_end = 0;
  1590.     struct rx_nfa_state * loop_exp_start = 0;
  1591.     struct rx_nfa_state * loop_exp_end = 0;
  1592.  
  1593.     return (rx_build_nfa (rx, rexp->params.pair.left,
  1594.                   &star_start, &star_end)
  1595.         && rx_build_nfa (rx, rexp->params.pair.right,
  1596.                  &loop_exp_start, &loop_exp_end)
  1597.         && star_start
  1598.         && star_end
  1599.         && loop_exp_end
  1600.         && loop_exp_start
  1601.         && rx_nfa_edge (rx, ne_epsilon, star_start, *end)
  1602.         && rx_nfa_edge (rx, ne_epsilon, *start, star_start)
  1603.         && rx_nfa_edge (rx, ne_epsilon, star_end, *end)
  1604.  
  1605.         && rx_nfa_edge (rx, ne_epsilon, star_end, loop_exp_start)
  1606.         && rx_nfa_edge (rx, ne_epsilon, loop_exp_end, star_start));
  1607.       }
  1608.  
  1609.  
  1610.     case r_concat:
  1611.       {
  1612.     struct rx_nfa_state *shared = 0;
  1613.     return
  1614.       (rx_build_nfa (rx, rexp->params.pair.left, start, &shared)
  1615.        && rx_build_nfa (rx, rexp->params.pair.right, &shared, end));
  1616.       }
  1617.  
  1618.     case r_alternate:
  1619.       {
  1620.     struct rx_nfa_state *ls = 0;
  1621.     struct rx_nfa_state *le = 0;
  1622.     struct rx_nfa_state *rs = 0;
  1623.     struct rx_nfa_state *re = 0;
  1624.     return (rx_build_nfa (rx, rexp->params.pair.left, &ls, &le)
  1625.         && rx_build_nfa (rx, rexp->params.pair.right, &rs, &re)
  1626.         && rx_nfa_edge (rx, ne_epsilon, *start, ls)
  1627.         && rx_nfa_edge (rx, ne_epsilon, *start, rs)
  1628.         && rx_nfa_edge (rx, ne_epsilon, le, *end)
  1629.         && rx_nfa_edge (rx, ne_epsilon, re, *end));
  1630.       }
  1631.  
  1632.     case r_side_effect:
  1633.       edge = rx_nfa_edge (rx, ne_side_effect, *start, *end);
  1634.       if (!edge)
  1635.     return 0;
  1636.       edge->params.side_effect = rexp->params.side_effect;
  1637.       return 1;
  1638.     }
  1639.  
  1640.   /* this should never happen */
  1641.   return 0;
  1642. }
  1643.  
  1644.  
  1645. /* RX_NAME_NFA_STATES identifies all nodes with outgoing non-epsilon
  1646.  * transitions.  Only these nodes can occur in super-states.  
  1647.  * All nodes are given an integer id. 
  1648.  * The id is non-negative if the node has non-epsilon out-transitions, negative
  1649.  * otherwise (this is because we want the non-negative ids to be used as 
  1650.  * array indexes in a few places).
  1651.  */
  1652.  
  1653. #ifdef __STDC__
  1654. RX_DECL void
  1655. rx_name_nfa_states (struct rx *rx)
  1656. #else
  1657. RX_DECL void
  1658. rx_name_nfa_states (rx)
  1659.      struct rx *rx;
  1660. #endif
  1661. {
  1662.   struct rx_nfa_state *n = rx->nfa_states;
  1663.  
  1664.   rx->nodec = 0;
  1665.   rx->epsnodec = -1;
  1666.  
  1667.   while (n)
  1668.     {
  1669.       struct rx_nfa_edge *e = n->edges;
  1670.  
  1671.       if (n->is_start)
  1672.     n->eclosure_needed = 1;
  1673.  
  1674.       while (e)
  1675.     {
  1676.       switch (e->type)
  1677.         {
  1678.         case ne_epsilon:
  1679.         case ne_side_effect:
  1680.           break;
  1681.  
  1682.         case ne_cset:
  1683.           n->id = rx->nodec++;
  1684.           {
  1685.         struct rx_nfa_edge *from_n = n->edges;
  1686.         while (from_n)
  1687.           {
  1688.             from_n->dest->eclosure_needed = 1;
  1689.             from_n = from_n->next;
  1690.           }
  1691.           }
  1692.           goto cont;
  1693.         }
  1694.       e = e->next;
  1695.     }
  1696.       n->id = rx->epsnodec--;
  1697.     cont:
  1698.       n = n->next;
  1699.     }
  1700.   rx->epsnodec = -rx->epsnodec;
  1701. }
  1702.  
  1703.  
  1704. /* This page: data structures for the static part of the nfa->supernfa
  1705.  * translation.
  1706.  *
  1707.  * There are side effect lists -- lists of side effects occuring
  1708.  * along an uninterrupted, acyclic path of side-effect epsilon edges.
  1709.  * Such paths are collapsed to single edges in the course of computing
  1710.  * epsilon closures.  Such single edges are labled with a list of all
  1711.  * the side effects entailed in crossing them.  Like lists of side
  1712.  * effects are made == by the constructors below.
  1713.  *
  1714.  * There are also nfa state sets.  These are used to hold a list of all
  1715.  * states reachable from a starting state for a given type of transition
  1716.  * and side effect list.   These are also hash-consed.
  1717.  */
  1718.  
  1719. /* The next several functions compare, construct, etc. lists of side
  1720.  * effects.  See ECLOSE_NFA (below) for details.
  1721.  */
  1722.  
  1723. /* Ordering of rx_se_list
  1724.  * (-1, 0, 1 return value convention).
  1725.  */
  1726.  
  1727. #ifdef __STDC__
  1728. static int 
  1729. se_list_cmp (void * va, void * vb)
  1730. #else
  1731. static int 
  1732. se_list_cmp (va, vb)
  1733.      void * va;
  1734.      void * vb;
  1735. #endif
  1736. {
  1737.   struct rx_se_list * a = (struct rx_se_list *)va;
  1738.   struct rx_se_list * b = (struct rx_se_list *)vb;
  1739.  
  1740.   return ((va == vb)
  1741.       ? 0
  1742.       : (!va
  1743.          ? -1
  1744.          : (!vb
  1745.         ? 1
  1746.         : ((long)a->car < (long)b->car
  1747.            ? 1
  1748.            : ((long)a->car > (long)b->car
  1749.               ? -1
  1750.               : se_list_cmp ((void *)a->cdr, (void *)b->cdr))))));
  1751. }
  1752.  
  1753.  
  1754. #ifdef __STDC__
  1755. static int 
  1756. se_list_equal (void * va, void * vb)
  1757. #else
  1758. static int 
  1759. se_list_equal (va, vb)
  1760.      void * va;
  1761.      void * vb;
  1762. #endif
  1763. {
  1764.   return !(se_list_cmp (va, vb));
  1765. }
  1766.  
  1767. static struct rx_hash_rules se_list_hash_rules =
  1768. {
  1769.   se_list_equal,
  1770.   compiler_hash_alloc,
  1771.   compiler_free_hash,
  1772.   compiler_hash_item_alloc,
  1773.   compiler_free_hash_item
  1774. };
  1775.  
  1776.  
  1777. #ifdef __STDC__
  1778. static struct rx_se_list * 
  1779. side_effect_cons (struct rx * rx,
  1780.           void * se, struct rx_se_list * list)
  1781. #else
  1782. static struct rx_se_list * 
  1783. side_effect_cons (rx, se, list)
  1784.      struct rx * rx;
  1785.      void * se;
  1786.      struct rx_se_list * list;
  1787. #endif
  1788. {
  1789.   struct rx_se_list * l;
  1790.   l = ((struct rx_se_list *) malloc (sizeof (*l)));
  1791.   if (!l)
  1792.     return 0;
  1793.   l->car = se;
  1794.   l->cdr = list;
  1795.   return l;
  1796. }
  1797.  
  1798.  
  1799. #ifdef __STDC__
  1800. static struct rx_se_list *
  1801. hash_cons_se_prog (struct rx * rx,
  1802.            struct rx_hash * memo,
  1803.            void * car, struct rx_se_list * cdr)
  1804. #else
  1805. static struct rx_se_list *
  1806. hash_cons_se_prog (rx, memo, car, cdr)
  1807.      struct rx * rx;
  1808.      struct rx_hash * memo;
  1809.      void * car;
  1810.      struct rx_se_list * cdr;
  1811. #endif
  1812. {
  1813.   long hash = (long)car ^ (long)cdr;
  1814.   struct rx_se_list template;
  1815.  
  1816.   template.car = car;
  1817.   template.cdr = cdr;
  1818.   {
  1819.     struct rx_hash_item * it = rx_hash_store (memo, hash,
  1820.                           (void *)&template,
  1821.                           &se_list_hash_rules);
  1822.     if (!it)
  1823.       return 0;
  1824.     if (it->data == (void *)&template)
  1825.       {
  1826.     struct rx_se_list * consed;
  1827.     consed = (struct rx_se_list *) malloc (sizeof (*consed));
  1828.     *consed = template;
  1829.     it->data = (void *)consed;
  1830.       }
  1831.     return (struct rx_se_list *)it->data;
  1832.   }
  1833. }
  1834.      
  1835.  
  1836. #ifdef __STDC__
  1837. static struct rx_se_list *
  1838. hash_se_prog (struct rx * rx, struct rx_hash * memo, struct rx_se_list * prog)
  1839. #else
  1840. static struct rx_se_list *
  1841. hash_se_prog (rx, memo, prog)
  1842.      struct rx * rx;
  1843.      struct rx_hash * memo;
  1844.      struct rx_se_list * prog;
  1845. #endif
  1846. {
  1847.   struct rx_se_list * answer = 0;
  1848.   while (prog)
  1849.     {
  1850.       answer = hash_cons_se_prog (rx, memo, prog->car, answer);
  1851.       if (!answer)
  1852.     return 0;
  1853.       prog = prog->cdr;
  1854.     }
  1855.   return answer;
  1856. }
  1857.  
  1858. #ifdef __STDC__
  1859. static int 
  1860. nfa_set_cmp (void * va, void * vb)
  1861. #else
  1862. static int 
  1863. nfa_set_cmp (va, vb)
  1864.      void * va;
  1865.      void * vb;
  1866. #endif
  1867. {
  1868.   struct rx_nfa_state_set * a = (struct rx_nfa_state_set *)va;
  1869.   struct rx_nfa_state_set * b = (struct rx_nfa_state_set *)vb;
  1870.  
  1871.   return ((va == vb)
  1872.       ? 0
  1873.       : (!va
  1874.          ? -1
  1875.          : (!vb
  1876.         ? 1
  1877.         : (a->car->id < b->car->id
  1878.            ? 1
  1879.            : (a->car->id > b->car->id
  1880.               ? -1
  1881.               : nfa_set_cmp ((void *)a->cdr, (void *)b->cdr))))));
  1882. }
  1883.  
  1884. #ifdef __STDC__
  1885. static int 
  1886. nfa_set_equal (void * va, void * vb)
  1887. #else
  1888. static int 
  1889. nfa_set_equal (va, vb)
  1890.      void * va;
  1891.      void * vb;
  1892. #endif
  1893. {
  1894.   return !nfa_set_cmp (va, vb);
  1895. }
  1896.  
  1897. static struct rx_hash_rules nfa_set_hash_rules =
  1898. {
  1899.   nfa_set_equal,
  1900.   compiler_hash_alloc,
  1901.   compiler_free_hash,
  1902.   compiler_hash_item_alloc,
  1903.   compiler_free_hash_item
  1904. };
  1905.  
  1906.  
  1907. #ifdef __STDC__
  1908. static struct rx_nfa_state_set * 
  1909. nfa_set_cons (struct rx * rx,
  1910.           struct rx_hash * memo, struct rx_nfa_state * state,
  1911.           struct rx_nfa_state_set * set)
  1912. #else
  1913. static struct rx_nfa_state_set * 
  1914. nfa_set_cons (rx, memo, state, set)
  1915.      struct rx * rx;
  1916.      struct rx_hash * memo;
  1917.      struct rx_nfa_state * state;
  1918.      struct rx_nfa_state_set * set;
  1919. #endif
  1920. {
  1921.   struct rx_nfa_state_set template;
  1922.   struct rx_hash_item * node;
  1923.   template.car = state;
  1924.   template.cdr = set;
  1925.   node = rx_hash_store (memo,
  1926.             (((long)state) >> 8) ^ (long)set,
  1927.             &template, &nfa_set_hash_rules);
  1928.   if (!node)
  1929.     return 0;
  1930.   if (node->data == &template)
  1931.     {
  1932.       struct rx_nfa_state_set * l;
  1933.       l = (struct rx_nfa_state_set *) malloc (sizeof (*l));
  1934.       node->data = (void *) l;
  1935.       if (!l)
  1936.     return 0;
  1937.       *l = template;
  1938.     }
  1939.   return (struct rx_nfa_state_set *)node->data;
  1940. }
  1941.  
  1942.  
  1943. #ifdef __STDC__
  1944. static struct rx_nfa_state_set * 
  1945. nfa_set_enjoin (struct rx * rx,
  1946.         struct rx_hash * memo, struct rx_nfa_state * state,
  1947.         struct rx_nfa_state_set * set)
  1948. #else
  1949. static struct rx_nfa_state_set * 
  1950. nfa_set_enjoin (rx, memo, state, set)
  1951.      struct rx * rx;
  1952.      struct rx_hash * memo;
  1953.      struct rx_nfa_state * state;
  1954.      struct rx_nfa_state_set * set;
  1955. #endif
  1956. {
  1957.   if (!set || state->id < set->car->id)
  1958.     return nfa_set_cons (rx, memo, state, set);
  1959.   if (state->id == set->car->id)
  1960.     return set;
  1961.   else
  1962.     {
  1963.       struct rx_nfa_state_set * newcdr
  1964.     = nfa_set_enjoin (rx, memo, state, set->cdr);
  1965.       if (newcdr != set->cdr)
  1966.     set = nfa_set_cons (rx, memo, set->car, newcdr);
  1967.       return set;
  1968.     }
  1969. }
  1970.  
  1971.  
  1972.  
  1973. /* This page: computing epsilon closures.  The closures aren't total.
  1974.  * Each node's closures are partitioned according to the side effects entailed
  1975.  * along the epsilon edges.  Return true on success.
  1976.  */ 
  1977.  
  1978. struct eclose_frame
  1979. {
  1980.   struct rx_se_list *prog_backwards;
  1981. };
  1982.  
  1983.  
  1984. #ifdef __STDC__
  1985. static int 
  1986. eclose_node (struct rx *rx, struct rx_nfa_state *outnode,
  1987.          struct rx_nfa_state *node, struct eclose_frame *frame)
  1988. #else
  1989. static int 
  1990. eclose_node (rx, outnode, node, frame)
  1991.      struct rx *rx;
  1992.      struct rx_nfa_state *outnode;
  1993.      struct rx_nfa_state *node;
  1994.      struct eclose_frame *frame;
  1995. #endif
  1996. {
  1997.   struct rx_nfa_edge *e = node->edges;
  1998.  
  1999.   /* For each node, we follow all epsilon paths to build the closure.
  2000.    * The closure omits nodes that have only epsilon edges.
  2001.    * The closure is split into partial closures -- all the states in
  2002.    * a partial closure are reached by crossing the same list of
  2003.    * of side effects (though not necessarily the same path).
  2004.    */
  2005.   if (node->mark)
  2006.     return 1;
  2007.   node->mark = 1;
  2008.  
  2009.   if (node->id >= 0 || node->is_final)
  2010.     {
  2011.       struct rx_possible_future **ec;
  2012.       struct rx_se_list * prog_in_order
  2013.     = ((struct rx_se_list *)hash_se_prog (rx,
  2014.                           &rx->se_list_memo,
  2015.                           frame->prog_backwards));
  2016.       int cmp;
  2017.  
  2018.       ec = &outnode->futures;
  2019.  
  2020.       while (*ec)
  2021.     {
  2022.       cmp = se_list_cmp ((void *)(*ec)->effects, (void *)prog_in_order);
  2023.       if (cmp <= 0)
  2024.         break;
  2025.       ec = &(*ec)->next;
  2026.     }
  2027.       if (!*ec || (cmp < 0))
  2028.     {
  2029.       struct rx_possible_future * saved = *ec;
  2030.       *ec = rx_possible_future (rx, prog_in_order);
  2031.       (*ec)->next = saved;
  2032.       if (!*ec)
  2033.         return 0;
  2034.     }
  2035.       if (node->id >= 0)
  2036.     {
  2037.       (*ec)->destset = nfa_set_enjoin (rx, &rx->set_list_memo,
  2038.                        node, (*ec)->destset);
  2039.       if (!(*ec)->destset)
  2040.         return 0;
  2041.     }
  2042.     }
  2043.  
  2044.   while (e)
  2045.     {
  2046.       switch (e->type)
  2047.     {
  2048.     case ne_epsilon:
  2049.       if (!eclose_node (rx, outnode, e->dest, frame))
  2050.         return 0;
  2051.       break;
  2052.     case ne_side_effect:
  2053.       {
  2054.         frame->prog_backwards = side_effect_cons (rx, 
  2055.                               e->params.side_effect,
  2056.                               frame->prog_backwards);
  2057.         if (!frame->prog_backwards)
  2058.           return 0;
  2059.         if (!eclose_node (rx, outnode, e->dest, frame))
  2060.           return 0;
  2061.         {
  2062.           struct rx_se_list * dying = frame->prog_backwards;
  2063.           frame->prog_backwards = frame->prog_backwards->cdr;
  2064.           free ((char *)dying);
  2065.         }
  2066.         break;
  2067.       }
  2068.     default:
  2069.       break;
  2070.     }
  2071.       e = e->next;
  2072.     }
  2073.   node->mark = 0;
  2074.   return 1;
  2075. }
  2076.  
  2077.  
  2078. #ifdef __STDC__
  2079. RX_DECL int 
  2080. rx_eclose_nfa (struct rx *rx)
  2081. #else
  2082. RX_DECL int 
  2083. rx_eclose_nfa (rx)
  2084.      struct rx *rx;
  2085. #endif
  2086. {
  2087.   struct rx_nfa_state *n = rx->nfa_states;
  2088.   struct eclose_frame frame;
  2089.   static int rx_id = 0;
  2090.   
  2091.   frame.prog_backwards = 0;
  2092.   rx->rx_id = rx_id++;
  2093.   bzero (&rx->se_list_memo, sizeof (rx->se_list_memo));
  2094.   bzero (&rx->set_list_memo, sizeof (rx->set_list_memo));
  2095.   while (n)
  2096.     {
  2097.       n->futures = 0;
  2098.       if (n->eclosure_needed && !eclose_node (rx, n, n, &frame))
  2099.     return 0;
  2100.       /* clear_marks (rx); */
  2101.       n = n->next;
  2102.     }
  2103.   return 1;
  2104. }
  2105.  
  2106.  
  2107. /* This deletes epsilon edges from an NFA.  After running eclose_node,
  2108.  * we have no more need for these edges.  They are removed to simplify
  2109.  * further operations on the NFA.
  2110.  */
  2111.  
  2112. #ifdef __STDC__
  2113. RX_DECL void 
  2114. rx_delete_epsilon_transitions (struct rx *rx)
  2115. #else
  2116. RX_DECL void 
  2117. rx_delete_epsilon_transitions (rx)
  2118.      struct rx *rx;
  2119. #endif
  2120. {
  2121.   struct rx_nfa_state *n = rx->nfa_states;
  2122.   struct rx_nfa_edge **e;
  2123.  
  2124.   while (n)
  2125.     {
  2126.       e = &n->edges;
  2127.       while (*e)
  2128.     {
  2129.       struct rx_nfa_edge *t;
  2130.       switch ((*e)->type)
  2131.         {
  2132.         case ne_epsilon:
  2133.         case ne_side_effect:
  2134.           t = *e;
  2135.           *e = t->next;
  2136.           rx_free_nfa_edge (t);
  2137.           break;
  2138.  
  2139.         default:
  2140.           e = &(*e)->next;
  2141.           break;
  2142.         }
  2143.     }
  2144.       n = n->next;
  2145.     }
  2146. }
  2147.  
  2148.  
  2149. /* This page: storing the nfa in a contiguous region of memory for
  2150.  * subsequent conversion to a super-nfa.
  2151.  */
  2152.  
  2153. /* This is for qsort on an array of nfa_states. The order
  2154.  * is based on state ids and goes 
  2155.  *        [0...MAX][MIN..-1] where (MAX>=0) and (MIN<0)
  2156.  * This way, positive ids double as array indices.
  2157.  */
  2158.  
  2159. #ifdef __STDC__
  2160. static int 
  2161. nfacmp (void * va, void * vb)
  2162. #else
  2163. static int 
  2164. nfacmp (va, vb)
  2165.      void * va;
  2166.      void * vb;
  2167. #endif
  2168. {
  2169.   struct rx_nfa_state **a = (struct rx_nfa_state **)va;
  2170.   struct rx_nfa_state **b = (struct rx_nfa_state **)vb;
  2171.   return (*a == *b        /* &&&& 3.18 */
  2172.       ? 0
  2173.       : (((*a)->id < 0) == ((*b)->id < 0)
  2174.          ? (((*a)->id  < (*b)->id) ? -1 : 1)
  2175.          : (((*a)->id < 0)
  2176.         ? 1 : -1)));
  2177. }
  2178.  
  2179. #ifdef __STDC__
  2180. static int 
  2181. count_hash_nodes (struct rx_hash * st)
  2182. #else
  2183. static int 
  2184. count_hash_nodes (st)
  2185.      struct rx_hash * st;
  2186. #endif
  2187. {
  2188.   int x;
  2189.   int count = 0;
  2190.   for (x = 0; x < 13; ++x)
  2191.     count += ((st->children[x])
  2192.           ? count_hash_nodes (st->children[x])
  2193.           : st->bucket_size[x]);
  2194.   
  2195.   return count;
  2196. }
  2197.  
  2198.  
  2199. #ifdef __STDC__
  2200. static void 
  2201. se_memo_freer (struct rx_hash_item * node)
  2202. #else
  2203. static void 
  2204. se_memo_freer (node)
  2205.      struct rx_hash_item * node;
  2206. #endif
  2207. {
  2208.   free ((char *)node->data);
  2209. }
  2210.  
  2211.  
  2212. #ifdef __STDC__
  2213. static void 
  2214. nfa_set_freer (struct rx_hash_item * node)
  2215. #else
  2216. static void 
  2217. nfa_set_freer (node)
  2218.      struct rx_hash_item * node;
  2219. #endif
  2220. {
  2221.   free ((char *)node->data);
  2222. }
  2223.  
  2224.  
  2225. /* This copies an entire NFA into a single malloced block of memory.
  2226.  * Mostly this is for compatability with regex.c, though it is convenient
  2227.  * to have the nfa nodes in an array.
  2228.  */
  2229.  
  2230. #ifdef __STDC__
  2231. RX_DECL int 
  2232. rx_compactify_nfa (struct rx *rx,
  2233.            void **mem, unsigned long *size)
  2234. #else
  2235. RX_DECL int 
  2236. rx_compactify_nfa (rx, mem, size)
  2237.      struct rx *rx;
  2238.      void **mem;
  2239.      unsigned long *size;
  2240. #endif
  2241. {
  2242.   int total_nodec;
  2243.   struct rx_nfa_state *n;
  2244.   int edgec = 0;
  2245.   int eclosec = 0;
  2246.   int se_list_consc = count_hash_nodes (&rx->se_list_memo);
  2247.   int nfa_setc = count_hash_nodes (&rx->set_list_memo);
  2248.   unsigned long total_size;
  2249.  
  2250.   /* This takes place in two stages.   First, the total size of the
  2251.    * nfa is computed, then structures are copied.  
  2252.    */   
  2253.   n = rx->nfa_states;
  2254.   total_nodec = 0;
  2255.   while (n)
  2256.     {
  2257.       struct rx_nfa_edge *e = n->edges;
  2258.       struct rx_possible_future *ec = n->futures;
  2259.       ++total_nodec;
  2260.       while (e)
  2261.     {
  2262.       ++edgec;
  2263.       e = e->next;
  2264.     }
  2265.       while (ec)
  2266.     {
  2267.       ++eclosec;
  2268.       ec = ec->next;
  2269.     }
  2270.       n = n->next;
  2271.     }
  2272.  
  2273.   total_size = (total_nodec * sizeof (struct rx_nfa_state)
  2274.         + edgec * rx_sizeof_bitset (rx->local_cset_size)
  2275.         + edgec * sizeof (struct rx_nfa_edge)
  2276.         + nfa_setc * sizeof (struct rx_nfa_state_set)
  2277.         + eclosec * sizeof (struct rx_possible_future)
  2278.         + se_list_consc * sizeof (struct rx_se_list)
  2279.         + rx->reserved);
  2280.  
  2281.   if (total_size > *size)
  2282.     {
  2283.       *mem = remalloc (*mem, total_size);
  2284.       if (*mem)
  2285.     *size = total_size;
  2286.       else
  2287.     return 0;
  2288.     }
  2289.   /* Now we've allocated the memory; this copies the NFA. */
  2290.   {
  2291.     static struct rx_nfa_state **scratch = 0;
  2292.     static int scratch_alloc = 0;
  2293.     struct rx_nfa_state *state_base = (struct rx_nfa_state *) * mem;
  2294.     struct rx_nfa_state *new_state = state_base;
  2295.     struct rx_nfa_edge *new_edge =
  2296.       (struct rx_nfa_edge *)
  2297.     ((char *) state_base + total_nodec * sizeof (struct rx_nfa_state));
  2298.     struct rx_se_list * new_se_list =
  2299.       (struct rx_se_list *)
  2300.     ((char *)new_edge + edgec * sizeof (struct rx_nfa_edge));
  2301.     struct rx_possible_future *new_close =
  2302.       ((struct rx_possible_future *)
  2303.        ((char *) new_se_list
  2304.     + se_list_consc * sizeof (struct rx_se_list)));
  2305.     struct rx_nfa_state_set * new_nfa_set =
  2306.       ((struct rx_nfa_state_set *)
  2307.        ((char *)new_close + eclosec * sizeof (struct rx_possible_future)));
  2308.     char *new_bitset =
  2309.       ((char *) new_nfa_set + nfa_setc * sizeof (struct rx_nfa_state_set));
  2310.     int x;
  2311.     struct rx_nfa_state *n;
  2312.  
  2313.     if (scratch_alloc < total_nodec)
  2314.       {
  2315.     scratch = ((struct rx_nfa_state **)
  2316.            remalloc (scratch, total_nodec * sizeof (*scratch)));
  2317.     if (scratch)
  2318.       scratch_alloc = total_nodec;
  2319.     else
  2320.       {
  2321.         scratch_alloc = 0;
  2322.         return 0;
  2323.       }
  2324.       }
  2325.  
  2326.     for (x = 0, n = rx->nfa_states; n; n = n->next)
  2327.       scratch[x++] = n;
  2328.  
  2329.     qsort (scratch, total_nodec,
  2330.        sizeof (struct rx_nfa_state *), (int (*)())nfacmp);
  2331.  
  2332.     for (x = 0; x < total_nodec; ++x)
  2333.       {
  2334.     struct rx_possible_future *eclose = scratch[x]->futures;
  2335.     struct rx_nfa_edge *edge = scratch[x]->edges;
  2336.     struct rx_nfa_state *cn = new_state++;
  2337.     cn->futures = 0;
  2338.     cn->edges = 0;
  2339.     cn->next = (x == total_nodec - 1) ? 0 : (cn + 1);
  2340.     cn->id = scratch[x]->id;
  2341.     cn->is_final = scratch[x]->is_final;
  2342.     cn->is_start = scratch[x]->is_start;
  2343.     cn->mark = 0;
  2344.     while (edge)
  2345.       {
  2346.         int indx = (edge->dest->id < 0
  2347.              ? (total_nodec + edge->dest->id)
  2348.              : edge->dest->id);
  2349.         struct rx_nfa_edge *e = new_edge++;
  2350.         rx_Bitset cset = (rx_Bitset) new_bitset;
  2351.         new_bitset += rx_sizeof_bitset (rx->local_cset_size);
  2352.         rx_bitset_null (rx->local_cset_size, cset);
  2353.         rx_bitset_union (rx->local_cset_size, cset, edge->params.cset);
  2354.         e->next = cn->edges;
  2355.         cn->edges = e;
  2356.         e->type = edge->type;
  2357.         e->dest = state_base + indx;
  2358.         e->params.cset = cset;
  2359.         edge = edge->next;
  2360.       }
  2361.     while (eclose)
  2362.       {
  2363.         struct rx_possible_future *ec = new_close++;
  2364.         struct rx_hash_item * sp;
  2365.         struct rx_se_list ** sepos;
  2366.         struct rx_se_list * sesrc;
  2367.         struct rx_nfa_state_set * destlst;
  2368.         struct rx_nfa_state_set ** destpos;
  2369.         ec->next = cn->futures;
  2370.         cn->futures = ec;
  2371.         for (sepos = &ec->effects, sesrc = eclose->effects;
  2372.          sesrc;
  2373.          sesrc = sesrc->cdr, sepos = &(*sepos)->cdr)
  2374.           {
  2375.         sp = rx_hash_find (&rx->se_list_memo,
  2376.                    (long)sesrc->car ^ (long)sesrc->cdr,
  2377.                    sesrc, &se_list_hash_rules);
  2378.         if (sp->binding)
  2379.           {
  2380.             sesrc = (struct rx_se_list *)sp->binding;
  2381.             break;
  2382.           }
  2383.         *new_se_list = *sesrc;
  2384.         sp->binding = (void *)new_se_list;
  2385.         *sepos = new_se_list;
  2386.         ++new_se_list;
  2387.           }
  2388.         *sepos = sesrc;
  2389.         for (destpos = &ec->destset, destlst = eclose->destset;
  2390.          destlst;
  2391.          destpos = &(*destpos)->cdr, destlst = destlst->cdr)
  2392.           {
  2393.         sp = rx_hash_find (&rx->set_list_memo,
  2394.                    ((((long)destlst->car) >> 8)
  2395.                     ^ (long)destlst->cdr),
  2396.                    destlst, &nfa_set_hash_rules);
  2397.         if (sp->binding)
  2398.           {
  2399.             destlst = (struct rx_nfa_state_set *)sp->binding;
  2400.             break;
  2401.           }
  2402.         *new_nfa_set = *destlst;
  2403.         new_nfa_set->car = state_base + destlst->car->id;
  2404.         sp->binding = (void *)new_nfa_set;
  2405.         *destpos = new_nfa_set;
  2406.         ++new_nfa_set;
  2407.           }
  2408.         *destpos = destlst;
  2409.         eclose = eclose->next;
  2410.       }
  2411.       }
  2412.   }
  2413.   rx_free_hash_table (&rx->se_list_memo, se_memo_freer, &se_list_hash_rules);
  2414.   bzero (&rx->se_list_memo, sizeof (rx->se_list_memo));
  2415.   rx_free_hash_table (&rx->set_list_memo, nfa_set_freer, &nfa_set_hash_rules);
  2416.   bzero (&rx->set_list_memo, sizeof (rx->set_list_memo));
  2417.  
  2418.   rx_free_nfa (rx);
  2419.   rx->nfa_states = (struct rx_nfa_state *)*mem;
  2420.   return 1;
  2421. }
  2422.  
  2423.  
  2424. /* The functions in the next several pages define the lazy-NFA-conversion used
  2425.  * by matchers.  The input to this construction is an NFA such as 
  2426.  * is built by compactify_nfa (rx.c).  The output is the superNFA.
  2427.  */
  2428.  
  2429. /* Match engines can use arbitrary values for opcodes.  So, the parse tree 
  2430.  * is built using instructions names (enum rx_opcode), but the superstate
  2431.  * nfa is populated with mystery opcodes (void *).
  2432.  *
  2433.  * For convenience, here is an id table.  The opcodes are == to their inxs
  2434.  *
  2435.  * The lables in re_search_2 would make good values for instructions.
  2436.  */
  2437.  
  2438. void * rx_id_instruction_table[rx_num_instructions] =
  2439. {
  2440.   (void *) rx_backtrack_point,
  2441.   (void *) rx_do_side_effects,
  2442.   (void *) rx_cache_miss,
  2443.   (void *) rx_next_char,
  2444.   (void *) rx_backtrack,
  2445.   (void *) rx_error_inx
  2446. };
  2447.  
  2448.  
  2449.  
  2450. /* Memory mgt. for superstate graphs. */
  2451.  
  2452. #ifdef __STDC__
  2453. static char *
  2454. rx_cache_malloc (struct rx_cache * cache, int bytes)
  2455. #else
  2456. static char *
  2457. rx_cache_malloc (cache, bytes)
  2458.      struct rx_cache * cache;
  2459.      int bytes;
  2460. #endif
  2461. {
  2462.   while (cache->bytes_left < bytes)
  2463.     {
  2464.       if (cache->memory_pos)
  2465.     cache->memory_pos = cache->memory_pos->next;
  2466.       if (!cache->memory_pos)
  2467.     {
  2468.       cache->morecore (cache);
  2469.       if (!cache->memory_pos)
  2470.         return 0;
  2471.     }
  2472.       cache->bytes_left = cache->memory_pos->bytes;
  2473.       cache->memory_addr = ((char *)cache->memory_pos
  2474.                 + sizeof (struct rx_blocklist));
  2475.     }
  2476.   cache->bytes_left -= bytes;
  2477.   {
  2478.     char * addr = cache->memory_addr;
  2479.     cache->memory_addr += bytes;
  2480.     return addr;
  2481.   }
  2482. }
  2483.  
  2484. #ifdef __STDC__
  2485. static void
  2486. rx_cache_free (struct rx_cache * cache,
  2487.            struct rx_freelist ** freelist, char * mem)
  2488. #else
  2489. static void
  2490. rx_cache_free (cache, freelist, mem)
  2491.      struct rx_cache * cache;
  2492.      struct rx_freelist ** freelist;
  2493.      char * mem;
  2494. #endif
  2495. {
  2496.   struct rx_freelist * it = (struct rx_freelist *)mem;
  2497.   it->next = *freelist;
  2498.   *freelist = it;
  2499. }
  2500.  
  2501.  
  2502. /* The partially instantiated superstate graph has a transition 
  2503.  * table at every node.  There is one entry for every character.
  2504.  * This fills in the transition for a set.
  2505.  */
  2506. #ifdef __STDC__
  2507. static void 
  2508. install_transition (struct rx_superstate *super,
  2509.             struct rx_inx *answer, rx_Bitset trcset) 
  2510. #else
  2511. static void 
  2512. install_transition (super, answer, trcset)
  2513.      struct rx_superstate *super;
  2514.      struct rx_inx *answer;
  2515.      rx_Bitset trcset;
  2516. #endif
  2517. {
  2518.   struct rx_inx * transitions = super->transitions;
  2519.   int chr;
  2520.   for (chr = 0; chr < 256; )
  2521.     if (!*trcset)
  2522.       {
  2523.     ++trcset;
  2524.     chr += 32;
  2525.       }
  2526.     else
  2527.       {
  2528.     RX_subset sub = *trcset;
  2529.     RX_subset mask = 1;
  2530.     int bound = chr + 32;
  2531.     while (chr < bound)
  2532.       {
  2533.         if (sub & mask)
  2534.           transitions [chr] = *answer;
  2535.         ++chr;
  2536.         mask <<= 1;
  2537.       }
  2538.     ++trcset;
  2539.       }
  2540. }
  2541.  
  2542.  
  2543. #ifdef __STDC__
  2544. static int
  2545. qlen (struct rx_superstate * q)
  2546. #else
  2547. static int
  2548. qlen (q)
  2549.      struct rx_superstate * q;
  2550. #endif
  2551. {
  2552.   int count = 1;
  2553.   struct rx_superstate * it;
  2554.   if (!q)
  2555.     return 0;
  2556.   for (it = q->next_recyclable; it != q; it = it->next_recyclable)
  2557.     ++count;
  2558.   return count;
  2559. }
  2560.  
  2561. #ifdef __STDC__
  2562. static void
  2563. check_cache (struct rx_cache * cache)
  2564. #else
  2565. static void
  2566. check_cache (cache)
  2567.      struct rx_cache * cache;
  2568. #endif
  2569. {
  2570.   struct rx_cache * you_fucked_up = 0;
  2571.   int total = cache->superstates;
  2572.   int semi = cache->semifree_superstates;
  2573.   if (semi != qlen (cache->semifree_superstate))
  2574.     check_cache (you_fucked_up);
  2575.   if ((total - semi) != qlen (cache->lru_superstate))
  2576.     check_cache (you_fucked_up);
  2577. }
  2578.  
  2579. /* When a superstate is old and neglected, it can enter a 
  2580.  * semi-free state.  A semi-free state is slated to die.
  2581.  * Incoming transitions to a semi-free state are re-written
  2582.  * to cause an (interpreted) fault when they are taken.
  2583.  * The fault handler revives the semi-free state, patches
  2584.  * incoming transitions back to normal, and continues.
  2585.  *
  2586.  * The idea is basicly to free in two stages, aborting 
  2587.  * between the two if the state turns out to be useful again.
  2588.  * When a free is aborted, the rescued superstate is placed
  2589.  * in the most-favored slot to maximize the time until it
  2590.  * is next semi-freed.
  2591.  */
  2592.  
  2593. #ifdef __STDC__
  2594. static void
  2595. semifree_superstate (struct rx_cache * cache)
  2596. #else
  2597. static void
  2598. semifree_superstate (cache)
  2599.      struct rx_cache * cache;
  2600. #endif
  2601. {
  2602.   int disqualified = cache->semifree_superstates;
  2603.   if (disqualified == cache->superstates)
  2604.     return;
  2605.   while (cache->lru_superstate->locks)
  2606.     {
  2607.       cache->lru_superstate = cache->lru_superstate->next_recyclable;
  2608.       ++disqualified;
  2609.       if (disqualified == cache->superstates)
  2610.     return;
  2611.     }
  2612.   {
  2613.     struct rx_superstate * it = cache->lru_superstate;
  2614.     it->next_recyclable->prev_recyclable = it->prev_recyclable;
  2615.     it->prev_recyclable->next_recyclable = it->next_recyclable;
  2616.     cache->lru_superstate = (it == it->next_recyclable
  2617.                  ? 0
  2618.                  : it->next_recyclable);
  2619.     if (!cache->semifree_superstate)
  2620.       {
  2621.     cache->semifree_superstate = it;
  2622.     it->next_recyclable = it;
  2623.     it->prev_recyclable = it;
  2624.       }
  2625.     else
  2626.       {
  2627.     it->prev_recyclable = cache->semifree_superstate->prev_recyclable;
  2628.     it->next_recyclable = cache->semifree_superstate;
  2629.     it->prev_recyclable->next_recyclable = it;
  2630.     it->next_recyclable->prev_recyclable = it;
  2631.       }
  2632.     {
  2633.       struct rx_distinct_future *df;
  2634.       it->is_semifree = 1;
  2635.       ++cache->semifree_superstates;
  2636.       df = it->transition_refs;
  2637.       if (df)
  2638.     {
  2639.       df->prev_same_dest->next_same_dest = 0;
  2640.       for (df = it->transition_refs; df; df = df->next_same_dest)
  2641.         {
  2642.           df->future_frame.inx = cache->instruction_table[rx_cache_miss];
  2643.           df->future_frame.data = 0;
  2644.           df->future_frame.data_2 = (void *) df;
  2645.           /* If there are any NEXT-CHAR instruction frames that
  2646.            * refer to this state, we convert them to CACHE-MISS frames.
  2647.            */
  2648.           if (!df->effects
  2649.           && (df->edge->options->next_same_super_edge[0]
  2650.               == df->edge->options))
  2651.         install_transition (df->present, &df->future_frame,
  2652.                     df->edge->cset);
  2653.         }
  2654.       df = it->transition_refs;
  2655.       df->prev_same_dest->next_same_dest = df;
  2656.     }
  2657.     }
  2658.   }
  2659. }
  2660.  
  2661.  
  2662. #ifdef __STDC__
  2663. static void 
  2664. refresh_semifree_superstate (struct rx_cache * cache,
  2665.                  struct rx_superstate * super)
  2666. #else
  2667. static void 
  2668. refresh_semifree_superstate (cache, super)
  2669.      struct rx_cache * cache;
  2670.      struct rx_superstate * super;
  2671. #endif
  2672. {
  2673.   struct rx_distinct_future *df;
  2674.  
  2675.   if (super->transition_refs)
  2676.     {
  2677.       super->transition_refs->prev_same_dest->next_same_dest = 0; 
  2678.       for (df = super->transition_refs; df; df = df->next_same_dest)
  2679.     {
  2680.       df->future_frame.inx = cache->instruction_table[rx_next_char];
  2681.       df->future_frame.data = (void *) super->transitions;
  2682.       /* CACHE-MISS instruction frames that refer to this state,
  2683.        * must be converted to NEXT-CHAR frames.
  2684.        */
  2685.       if (!df->effects
  2686.           && (df->edge->options->next_same_super_edge[0]
  2687.           == df->edge->options))
  2688.         install_transition (df->present, &df->future_frame,
  2689.                 df->edge->cset);
  2690.     }
  2691.       super->transition_refs->prev_same_dest->next_same_dest
  2692.     = super->transition_refs;
  2693.     }
  2694.   if (cache->semifree_superstate == super)
  2695.     cache->semifree_superstate = (super->prev_recyclable == super
  2696.                   ? 0
  2697.                   : super->prev_recyclable);
  2698.   super->next_recyclable->prev_recyclable = super->prev_recyclable;
  2699.   super->prev_recyclable->next_recyclable = super->next_recyclable;
  2700.  
  2701.   if (!cache->lru_superstate)
  2702.     (cache->lru_superstate
  2703.      = super->next_recyclable
  2704.      = super->prev_recyclable
  2705.      = super);
  2706.   else
  2707.     {
  2708.       super->next_recyclable = cache->lru_superstate;
  2709.       super->prev_recyclable = cache->lru_superstate->prev_recyclable;
  2710.       super->next_recyclable->prev_recyclable = super;
  2711.       super->prev_recyclable->next_recyclable = super;
  2712.     }
  2713.   super->is_semifree = 0;
  2714.   --cache->semifree_superstates;
  2715. }
  2716.  
  2717. #ifdef __STDC__
  2718. static void
  2719. rx_refresh_this_superstate (struct rx_cache * cache, struct rx_superstate * superstate)
  2720. #else
  2721. static void
  2722. rx_refresh_this_superstate (cache, superstate)
  2723.      struct rx_cache * cache;
  2724.      struct rx_superstate * superstate;
  2725. #endif
  2726. {
  2727.   if (superstate->is_semifree)
  2728.     refresh_semifree_superstate (cache, superstate);
  2729.   else if (cache->lru_superstate == superstate)
  2730.     cache->lru_superstate = superstate->next_recyclable;
  2731.   else if (superstate != cache->lru_superstate->prev_recyclable)
  2732.     {
  2733.       superstate->next_recyclable->prev_recyclable
  2734.     = superstate->prev_recyclable;
  2735.       superstate->prev_recyclable->next_recyclable
  2736.     = superstate->next_recyclable;
  2737.       superstate->next_recyclable = cache->lru_superstate;
  2738.       superstate->prev_recyclable = cache->lru_superstate->prev_recyclable;
  2739.       superstate->next_recyclable->prev_recyclable = superstate;
  2740.       superstate->prev_recyclable->next_recyclable = superstate;
  2741.     }
  2742. }
  2743.  
  2744. #ifdef __STDC__
  2745. static void 
  2746. release_superset_low (struct rx_cache * cache,
  2747.              struct rx_superset *set)
  2748. #else
  2749. static void 
  2750. release_superset_low (cache, set)
  2751.      struct rx_cache * cache;
  2752.      struct rx_superset *set;
  2753. #endif
  2754. {
  2755.   if (!--set->refs)
  2756.     {
  2757.       if (set->cdr)
  2758.     release_superset_low (cache, set->cdr);
  2759.  
  2760.       set->starts_for = 0;
  2761.  
  2762.       rx_hash_free
  2763.     (rx_hash_find
  2764.      (&cache->superset_table,
  2765.       (unsigned long)set->car ^ set->id ^ (unsigned long)set->cdr,
  2766.       (void *)set,
  2767.       &cache->superset_hash_rules),
  2768.      &cache->superset_hash_rules);
  2769.       rx_cache_free (cache, &cache->free_supersets, (char *)set);
  2770.     }
  2771. }
  2772.  
  2773. #ifdef __STDC__
  2774. RX_DECL void 
  2775. rx_release_superset (struct rx *rx,
  2776.              struct rx_superset *set)
  2777. #else
  2778. RX_DECL void 
  2779. rx_release_superset (rx, set)
  2780.      struct rx *rx;
  2781.      struct rx_superset *set;
  2782. #endif
  2783. {
  2784.   release_superset_low (rx->cache, set);
  2785. }
  2786.  
  2787. /* This tries to add a new superstate to the superstate freelist.
  2788.  * It might, as a result, free some edge pieces or hash tables.
  2789.  * If nothing can be freed because too many locks are being held, fail.
  2790.  */
  2791.  
  2792. #ifdef __STDC__
  2793. static int
  2794. rx_really_free_superstate (struct rx_cache * cache)
  2795. #else
  2796. static int
  2797. rx_really_free_superstate (cache)
  2798.      struct rx_cache * cache;
  2799. #endif
  2800. {
  2801.   int locked_superstates = 0;
  2802.   struct rx_superstate * it;
  2803.  
  2804.   if (!cache->superstates)
  2805.     return 0;
  2806.  
  2807.   {
  2808.     /* This is a total guess.  The idea is that we should expect as
  2809.      * many misses as we've recently experienced.  I.e., cache->misses
  2810.      * should be the same as cache->semifree_superstates.
  2811.      */
  2812.     while ((cache->hits + cache->misses) > cache->superstates_allowed)
  2813.       {
  2814.     cache->hits >>= 1;
  2815.     cache->misses >>= 1;
  2816.       }
  2817.     if (  ((cache->hits + cache->misses) * cache->semifree_superstates)
  2818.     < (cache->superstates         * cache->misses))
  2819.       {
  2820.     semifree_superstate (cache);
  2821.     semifree_superstate (cache);
  2822.       }
  2823.   }
  2824.  
  2825.   while (cache->semifree_superstate && cache->semifree_superstate->locks)
  2826.     {
  2827.       refresh_semifree_superstate (cache, cache->semifree_superstate);
  2828.       ++locked_superstates;
  2829.       if (locked_superstates == cache->superstates)
  2830.     return 0;
  2831.     }
  2832.  
  2833.   if (cache->semifree_superstate)
  2834.     {
  2835.       it = cache->semifree_superstate;
  2836.       it->next_recyclable->prev_recyclable = it->prev_recyclable;
  2837.       it->prev_recyclable->next_recyclable = it->next_recyclable;
  2838.       cache->semifree_superstate = ((it == it->next_recyclable)
  2839.                     ? 0
  2840.                     : it->next_recyclable);
  2841.       --cache->semifree_superstates;
  2842.     }
  2843.   else
  2844.     {
  2845.       while (cache->lru_superstate->locks)
  2846.     {
  2847.       cache->lru_superstate = cache->lru_superstate->next_recyclable;
  2848.       ++locked_superstates;
  2849.       if (locked_superstates == cache->superstates)
  2850.         return 0;
  2851.     }
  2852.       it = cache->lru_superstate;
  2853.       it->next_recyclable->prev_recyclable = it->prev_recyclable;
  2854.       it->prev_recyclable->next_recyclable = it->next_recyclable;
  2855.       cache->lru_superstate = ((it == it->next_recyclable)
  2856.                     ? 0
  2857.                     : it->next_recyclable);
  2858.     }
  2859.  
  2860.   if (it->transition_refs)
  2861.     {
  2862.       struct rx_distinct_future *df;
  2863.       for (df = it->transition_refs,
  2864.        df->prev_same_dest->next_same_dest = 0;
  2865.        df;
  2866.        df = df->next_same_dest)
  2867.     {
  2868.       df->future_frame.inx = cache->instruction_table[rx_cache_miss];
  2869.       df->future_frame.data = 0;
  2870.       df->future_frame.data_2 = (void *) df;
  2871.       df->future = 0;
  2872.     }
  2873.       it->transition_refs->prev_same_dest->next_same_dest =
  2874.     it->transition_refs;
  2875.     }
  2876.   {
  2877.     struct rx_super_edge *tc = it->edges;
  2878.     while (tc)
  2879.       {
  2880.     struct rx_distinct_future * df;
  2881.     struct rx_super_edge *tct = tc->next;
  2882.     df = tc->options;
  2883.     df->next_same_super_edge[1]->next_same_super_edge[0] = 0;
  2884.     while (df)
  2885.       {
  2886.         struct rx_distinct_future *dft = df;
  2887.         df = df->next_same_super_edge[0];
  2888.         
  2889.         
  2890.         if (dft->future && dft->future->transition_refs == dft)
  2891.           {
  2892.         dft->future->transition_refs = dft->next_same_dest;
  2893.         if (dft->future->transition_refs == dft)
  2894.           dft->future->transition_refs = 0;
  2895.           }
  2896.         dft->next_same_dest->prev_same_dest = dft->prev_same_dest;
  2897.         dft->prev_same_dest->next_same_dest = dft->next_same_dest;
  2898.         rx_cache_free (cache, &cache->free_discernable_futures,
  2899.                (char *)dft);
  2900.       }
  2901.     rx_cache_free (cache, &cache->free_transition_classes, (char *)tc);
  2902.     tc = tct;
  2903.       }
  2904.   }
  2905.   
  2906.   if (it->contents->superstate == it)
  2907.     it->contents->superstate = 0;
  2908.   release_superset_low (cache, it->contents);
  2909.   rx_cache_free (cache, &cache->free_superstates, (char *)it);
  2910.   --cache->superstates;
  2911.   return 1;
  2912. }
  2913.  
  2914. #ifdef __STDC__
  2915. static char *
  2916. rx_cache_get (struct rx_cache * cache,
  2917.           struct rx_freelist ** freelist)
  2918. #else
  2919. static char *
  2920. rx_cache_get (cache, freelist)
  2921.      struct rx_cache * cache;
  2922.      struct rx_freelist ** freelist;
  2923. #endif
  2924. {
  2925.   while (!*freelist && rx_really_free_superstate (cache))
  2926.     ;
  2927.   if (!*freelist)
  2928.     return 0;
  2929.   {
  2930.     struct rx_freelist * it = *freelist;
  2931.     *freelist = it->next;
  2932.     return (char *)it;
  2933.   }
  2934. }
  2935.  
  2936. #ifdef __STDC__
  2937. static char *
  2938. rx_cache_malloc_or_get (struct rx_cache * cache,
  2939.             struct rx_freelist ** freelist, int bytes)
  2940. #else
  2941. static char *
  2942. rx_cache_malloc_or_get (cache, freelist, bytes)
  2943.      struct rx_cache * cache;
  2944.      struct rx_freelist ** freelist;
  2945.      int bytes;
  2946. #endif
  2947. {
  2948.   if (!*freelist)
  2949.     {
  2950.       char * answer = rx_cache_malloc (cache, bytes);
  2951.       if (answer)
  2952.     return answer;
  2953.     }
  2954.  
  2955.   return rx_cache_get (cache, freelist);
  2956. }
  2957.  
  2958. #ifdef __STDC__
  2959. static char *
  2960. rx_cache_get_superstate (struct rx_cache * cache)
  2961. #else
  2962. static char *
  2963. rx_cache_get_superstate (cache)
  2964.       struct rx_cache * cache;
  2965. #endif
  2966. {
  2967.   char * answer;
  2968.   int bytes = (   sizeof (struct rx_superstate)
  2969.            +  cache->local_cset_size * sizeof (struct rx_inx));
  2970.   if (!cache->free_superstates
  2971.       && (cache->superstates < cache->superstates_allowed))
  2972.     {
  2973.       answer = rx_cache_malloc (cache, bytes);
  2974.       if (answer)
  2975.     {
  2976.       ++cache->superstates;
  2977.       return answer;
  2978.     }
  2979.     }
  2980.   answer = rx_cache_get (cache, &cache->free_superstates);
  2981.   if (!answer)
  2982.     {
  2983.       answer = rx_cache_malloc (cache, bytes);
  2984.       if (answer)
  2985.     ++cache->superstates_allowed;
  2986.     }
  2987.   ++cache->superstates;
  2988.   return answer;
  2989. }
  2990.  
  2991.  
  2992.  
  2993. #ifdef __STDC__
  2994. static int
  2995. supersetcmp (void * va, void * vb)
  2996. #else
  2997. static int
  2998. supersetcmp (va, vb)
  2999.      void * va;
  3000.      void * vb;
  3001. #endif
  3002. {
  3003.   struct rx_superset * a = (struct rx_superset *)va;
  3004.   struct rx_superset * b = (struct rx_superset *)vb;
  3005.   return (   (a == b)
  3006.       || (a && b && (a->car == b->car) && (a->cdr == b->cdr)));
  3007. }
  3008.  
  3009. #ifdef __STDC__
  3010. static struct rx_hash_item *
  3011. superset_allocator (struct rx_hash_rules * rules, void * val)
  3012. #else
  3013. static struct rx_hash_item *
  3014. superset_allocator (rules, val)
  3015.      struct rx_hash_rules * rules;
  3016.      void * val;
  3017. #endif
  3018. {
  3019.   struct rx_cache * cache
  3020.     = ((struct rx_cache *)
  3021.        ((char *)rules
  3022.     - (unsigned long)(&((struct rx_cache *)0)->superset_hash_rules)));
  3023.   struct rx_superset * template = (struct rx_superset *)val;
  3024.   struct rx_superset * newset
  3025.     = ((struct rx_superset *)
  3026.        rx_cache_malloc_or_get (cache,
  3027.                    &cache->free_supersets,
  3028.                    sizeof (*template)));
  3029.   if (!newset)
  3030.     return 0;
  3031.   newset->refs = 0;
  3032.   newset->car = template->car;
  3033.   newset->id = template->car->id;
  3034.   newset->cdr = template->cdr;
  3035.   newset->superstate = 0;
  3036.   rx_protect_superset (rx, template->cdr);
  3037.   newset->hash_item.data = (void *)newset;
  3038.   newset->hash_item.binding = 0;
  3039.   return &newset->hash_item;
  3040. }
  3041.  
  3042. #ifdef __STDC__
  3043. static struct rx_hash * 
  3044. super_hash_allocator (struct rx_hash_rules * rules)
  3045. #else
  3046. static struct rx_hash * 
  3047. super_hash_allocator (rules)
  3048.      struct rx_hash_rules * rules;
  3049. #endif
  3050. {
  3051.   struct rx_cache * cache
  3052.     = ((struct rx_cache *)
  3053.        ((char *)rules
  3054.     - (unsigned long)(&((struct rx_cache *)0)->superset_hash_rules)));
  3055.   return ((struct rx_hash *)
  3056.       rx_cache_malloc_or_get (cache,
  3057.                   &cache->free_hash, sizeof (struct rx_hash)));
  3058. }
  3059.  
  3060.  
  3061. #ifdef __STDC__
  3062. static void
  3063. super_hash_liberator (struct rx_hash * hash, struct rx_hash_rules * rules)
  3064. #else
  3065. static void
  3066. super_hash_liberator (hash, rules)
  3067.      struct rx_hash * hash;
  3068.      struct rx_hash_rules * rules;
  3069. #endif
  3070. {
  3071.   struct rx_cache * cache
  3072.     = ((struct rx_cache *)
  3073.        (char *)rules - (long)(&((struct rx_cache *)0)->superset_hash_rules));
  3074.   rx_cache_free (cache, &cache->free_hash, (char *)hash);
  3075. }
  3076.  
  3077. #ifdef __STDC__
  3078. static void
  3079. superset_hash_item_liberator (struct rx_hash_item * it,
  3080.                   struct rx_hash_rules * rules)
  3081. #else
  3082. static void
  3083. superset_hash_item_liberator (it, rules) /* Well, it does ya know. */
  3084.      struct rx_hash_item * it;
  3085.      struct rx_hash_rules * rules;
  3086. #endif
  3087. {
  3088. }
  3089.  
  3090. int rx_cache_bound = 128;
  3091. static int rx_default_cache_got = 0;
  3092.  
  3093. #ifdef __STDC__
  3094. static int
  3095. bytes_for_cache_size (int supers, int cset_size)
  3096. #else
  3097. static int
  3098. bytes_for_cache_size (supers, cset_size)
  3099.      int supers;
  3100.      int cset_size;
  3101. #endif
  3102. {
  3103.   /* What the hell is this? !!!*/
  3104.   return (int)
  3105.     ((float)supers *
  3106.      (  (1.03 * (float) (  rx_sizeof_bitset (cset_size)
  3107.              + sizeof (struct rx_super_edge)))
  3108.       + (1.80 * (float) sizeof (struct rx_possible_future))
  3109.       + (float) (  sizeof (struct rx_superstate)
  3110.          + cset_size * sizeof (struct rx_inx))));
  3111. }
  3112.  
  3113. #ifdef __STDC__
  3114. static void
  3115. rx_morecore (struct rx_cache * cache)
  3116. #else
  3117. static void
  3118. rx_morecore (cache)
  3119.      struct rx_cache * cache;
  3120. #endif
  3121. {
  3122.   if (rx_default_cache_got >= rx_cache_bound)
  3123.     return;
  3124.  
  3125.   rx_default_cache_got += 16;
  3126.   cache->superstates_allowed = rx_cache_bound;
  3127.   {
  3128.     struct rx_blocklist ** pos = &cache->memory;
  3129.     int size = bytes_for_cache_size (16, cache->local_cset_size);
  3130.     while (*pos)
  3131.       pos = &(*pos)->next;
  3132.     *pos = ((struct rx_blocklist *)
  3133.         malloc (size + sizeof (struct rx_blocklist))); 
  3134.     if (!*pos)
  3135.       return;
  3136.  
  3137.     (*pos)->next = 0;
  3138.     (*pos)->bytes = size;
  3139.     cache->memory_pos = *pos;
  3140.     cache->memory_addr = (char *)*pos + sizeof (**pos);
  3141.     cache->bytes_left = size;
  3142.   }
  3143. }
  3144.  
  3145. static struct rx_cache default_cache = 
  3146. {
  3147.   {
  3148.     supersetcmp,
  3149.     super_hash_allocator,
  3150.     super_hash_liberator,
  3151.     superset_allocator,
  3152.     superset_hash_item_liberator,
  3153.   },
  3154.   0,
  3155.   0,
  3156.   0,
  3157.   0,
  3158.   rx_morecore,
  3159.  
  3160.   0,
  3161.   0,
  3162.   0,
  3163.   0,
  3164.   0,
  3165.  
  3166.   0,
  3167.   0,
  3168.  
  3169.   0,
  3170.  
  3171.   0,
  3172.   0,
  3173.   0,
  3174.   0,
  3175.   128,
  3176.  
  3177.   256,
  3178.   rx_id_instruction_table,
  3179.  
  3180.   {
  3181.     0,
  3182.     0,
  3183.     {0},
  3184.     {0},
  3185.     {0}
  3186.   }
  3187. };
  3188.  
  3189. /* This adds an element to a superstate set.  These sets are lists, such
  3190.  * that lists with == elements are ==.  The empty set is returned by
  3191.  * superset_cons (rx, 0, 0) and is NOT equivelent to 
  3192.  * (struct rx_superset)0.
  3193.  */
  3194.  
  3195. #ifdef __STDC__
  3196. RX_DECL struct rx_superset *
  3197. rx_superset_cons (struct rx * rx,
  3198.           struct rx_nfa_state *car, struct rx_superset *cdr)
  3199. #else
  3200. RX_DECL struct rx_superset *
  3201. rx_superset_cons (rx, car, cdr)
  3202.      struct rx * rx;
  3203.      struct rx_nfa_state *car;
  3204.      struct rx_superset *cdr;
  3205. #endif
  3206. {
  3207.   struct rx_cache * cache = rx->cache;
  3208.   if (!car && !cdr)
  3209.     {
  3210.       if (!cache->empty_superset)
  3211.     {
  3212.       cache->empty_superset
  3213.         = ((struct rx_superset *)
  3214.            rx_cache_malloc_or_get (cache, &cache->free_supersets,
  3215.                        sizeof (struct rx_superset)));
  3216.       if (!cache->empty_superset)
  3217.         return 0;
  3218.       bzero (cache->empty_superset, sizeof (struct rx_superset));
  3219.       cache->empty_superset->refs = 1000;
  3220.     }
  3221.       return cache->empty_superset;
  3222.     }
  3223.   {
  3224.     struct rx_superset template;
  3225.     struct rx_hash_item * hit;
  3226.     template.car = car;
  3227.     template.cdr = cdr;
  3228.     template.id = car->id;
  3229.     hit = rx_hash_store (&cache->superset_table,
  3230.              (unsigned long)car ^ car->id ^ (unsigned long)cdr,
  3231.              (void *)&template,
  3232.              &cache->superset_hash_rules);
  3233.     return (hit
  3234.         ?  (struct rx_superset *)hit->data
  3235.         : 0);
  3236.   }
  3237. }
  3238.  
  3239. /* This computes a union of two NFA state sets.  The sets do not have the
  3240.  * same representation though.  One is a RX_SUPERSET structure (part
  3241.  * of the superstate NFA) and the other is an NFA_STATE_SET (part of the NFA).
  3242.  */
  3243.  
  3244. #ifdef __STDC__
  3245. RX_DECL struct rx_superset *
  3246. rx_superstate_eclosure_union
  3247.   (struct rx * rx, struct rx_superset *set, struct rx_nfa_state_set *ecl) 
  3248. #else
  3249. RX_DECL struct rx_superset *
  3250. rx_superstate_eclosure_union (rx, set, ecl)
  3251.      struct rx * rx;
  3252.      struct rx_superset *set;
  3253.      struct rx_nfa_state_set *ecl;
  3254. #endif
  3255. {
  3256.   if (!ecl)
  3257.     return set;
  3258.  
  3259.   if (!set->car)
  3260.     return rx_superset_cons (rx, ecl->car,
  3261.                  rx_superstate_eclosure_union (rx, set, ecl->cdr));
  3262.   if (set->car == ecl->car)
  3263.     return rx_superstate_eclosure_union (rx, set, ecl->cdr);
  3264.  
  3265.   {
  3266.     struct rx_superset * tail;
  3267.     struct rx_nfa_state * first;
  3268.  
  3269.     if (set->car > ecl->car)
  3270.       {
  3271.     tail = rx_superstate_eclosure_union (rx, set->cdr, ecl);
  3272.     first = set->car;
  3273.       }
  3274.     else
  3275.       {
  3276.     tail = rx_superstate_eclosure_union (rx, set, ecl->cdr);
  3277.     first = ecl->car;
  3278.       }
  3279.     if (!tail)
  3280.       return 0;
  3281.     else
  3282.       {
  3283.     struct rx_superset * answer;
  3284.     answer = rx_superset_cons (rx, first, tail);
  3285.     if (!answer)
  3286.       {
  3287.         rx_protect_superset (rx, tail);
  3288.         rx_release_superset (rx, tail);
  3289.         return 0;
  3290.       }
  3291.     else
  3292.       return answer;
  3293.       }
  3294.   }
  3295. }
  3296.  
  3297.  
  3298.  
  3299.  
  3300. /*
  3301.  * This makes sure that a list of rx_distinct_futures contains
  3302.  * a future for each possible set of side effects in the eclosure
  3303.  * of a given state.  This is some of the work of filling in a
  3304.  * superstate transition. 
  3305.  */
  3306.  
  3307. #ifdef __STDC__
  3308. static struct rx_distinct_future *
  3309. include_futures (struct rx *rx,
  3310.          struct rx_distinct_future *df, struct rx_nfa_state
  3311.          *state, struct rx_superstate *superstate) 
  3312. #else
  3313. static struct rx_distinct_future *
  3314. include_futures (rx, df, state, superstate)
  3315.      struct rx *rx;
  3316.      struct rx_distinct_future *df;
  3317.      struct rx_nfa_state *state;
  3318.      struct rx_superstate *superstate;
  3319. #endif
  3320. {
  3321.   struct rx_possible_future *future;
  3322.   struct rx_cache * cache = rx->cache;
  3323.   for (future = state->futures; future; future = future->next)
  3324.     {
  3325.       struct rx_distinct_future *dfp;
  3326.       struct rx_distinct_future *insert_before = 0;
  3327.       if (df)
  3328.     df->next_same_super_edge[1]->next_same_super_edge[0] = 0;
  3329.       for (dfp = df; dfp; dfp = dfp->next_same_super_edge[0])
  3330.     if (dfp->effects == future->effects)
  3331.       break;
  3332.     else
  3333.       {
  3334.         int order = rx->se_list_cmp (rx, dfp->effects, future->effects);
  3335.         if (order > 0)
  3336.           {
  3337.         insert_before = dfp;
  3338.         dfp = 0;
  3339.         break;
  3340.           }
  3341.       }
  3342.       if (df)
  3343.     df->next_same_super_edge[1]->next_same_super_edge[0] = df;
  3344.       if (!dfp)
  3345.     {
  3346.       dfp
  3347.         = ((struct rx_distinct_future *)
  3348.            rx_cache_malloc_or_get (cache, &cache->free_discernable_futures,
  3349.                        sizeof (struct rx_distinct_future)));
  3350.       if (!dfp)
  3351.         return 0;
  3352.       if (!df)
  3353.         {
  3354.           df = insert_before = dfp;
  3355.           df->next_same_super_edge[0] = df->next_same_super_edge[1] = df;
  3356.         }
  3357.       else if (!insert_before)
  3358.         insert_before = df;
  3359.       else if (insert_before == df)
  3360.         df = dfp;
  3361.  
  3362.       dfp->next_same_super_edge[0] = insert_before;
  3363.       dfp->next_same_super_edge[1]
  3364.         = insert_before->next_same_super_edge[1];
  3365.       dfp->next_same_super_edge[1]->next_same_super_edge[0] = dfp;
  3366.       dfp->next_same_super_edge[0]->next_same_super_edge[1] = dfp;
  3367.       dfp->next_same_dest = dfp->prev_same_dest = dfp;
  3368.       dfp->future = 0;
  3369.       dfp->present = superstate;
  3370.       dfp->future_frame.inx = rx->instruction_table[rx_cache_miss];
  3371.       dfp->future_frame.data = 0;
  3372.       dfp->future_frame.data_2 = (void *) dfp;
  3373.       dfp->side_effects_frame.inx
  3374.         = rx->instruction_table[rx_do_side_effects];
  3375.       dfp->side_effects_frame.data = 0;
  3376.       dfp->side_effects_frame.data_2 = (void *) dfp;
  3377.       dfp->effects = future->effects;
  3378.     }
  3379.     }
  3380.   return df;
  3381. }
  3382.  
  3383.  
  3384.  
  3385. /* This constructs a new superstate from its state set.  The only 
  3386.  * complexity here is memory management.
  3387.  */
  3388. #ifdef __STDC__
  3389. RX_DECL struct rx_superstate *
  3390. rx_superstate (struct rx *rx,
  3391.            struct rx_superset *set)
  3392. #else
  3393. RX_DECL struct rx_superstate *
  3394. rx_superstate (rx, set)
  3395.      struct rx *rx;
  3396.      struct rx_superset *set;
  3397. #endif
  3398. {
  3399.   struct rx_cache * cache = rx->cache;
  3400.   struct rx_superstate * superstate = 0;
  3401.  
  3402.   /* Does the superstate already exist in the cache? */
  3403.   if (set->superstate)
  3404.     {
  3405.       if (set->superstate->rx_id != rx->rx_id)
  3406.     {
  3407.       /* Aha.  It is in the cache, but belongs to a superstate
  3408.        * that refers to an NFA that no longer exists.
  3409.        * (We know it no longer exists because it was evidently
  3410.        *  stored in the same region of memory as the current nfa
  3411.        *  yet it has a different id.)
  3412.        */
  3413.       superstate = set->superstate;
  3414.       if (!superstate->is_semifree)
  3415.         {
  3416.           if (cache->lru_superstate == superstate)
  3417.         {
  3418.           cache->lru_superstate = superstate->next_recyclable;
  3419.           if (cache->lru_superstate == superstate)
  3420.             cache->lru_superstate = 0;
  3421.         }
  3422.           {
  3423.         superstate->next_recyclable->prev_recyclable
  3424.           = superstate->prev_recyclable;
  3425.         superstate->prev_recyclable->next_recyclable
  3426.           = superstate->next_recyclable;
  3427.         if (!cache->semifree_superstate)
  3428.           {
  3429.             (cache->semifree_superstate
  3430.              = superstate->next_recyclable
  3431.              = superstate->prev_recyclable
  3432.              = superstate);
  3433.           }
  3434.         else
  3435.           {
  3436.             superstate->next_recyclable = cache->semifree_superstate;
  3437.             superstate->prev_recyclable
  3438.               = cache->semifree_superstate->prev_recyclable;
  3439.             superstate->next_recyclable->prev_recyclable
  3440.               = superstate;
  3441.             superstate->prev_recyclable->next_recyclable
  3442.               = superstate;
  3443.             cache->semifree_superstate = superstate;
  3444.           }
  3445.         ++cache->semifree_superstates;
  3446.           }
  3447.         }
  3448.       set->superstate = 0;
  3449.       goto handle_cache_miss;
  3450.     }
  3451.       ++cache->hits;
  3452.       superstate = set->superstate;
  3453.  
  3454.       rx_refresh_this_superstate (cache, superstate);
  3455.       return superstate;
  3456.     }
  3457.  
  3458.  handle_cache_miss:
  3459.  
  3460.   /* This point reached only for cache misses. */
  3461.   ++cache->misses;
  3462. #if RX_DEBUG
  3463.   if (rx_debug_trace > 1)
  3464.     {
  3465.       struct rx_superset * setp = set;
  3466.       fprintf (stderr, "Building a superstet %d(%d): ", rx->rx_id, set);
  3467.       while (setp)
  3468.     {
  3469.       fprintf (stderr, "%d ", setp->id);
  3470.       setp = setp->cdr;
  3471.     }
  3472.       fprintf (stderr, "(%d)\n", set);
  3473.     }
  3474. #endif
  3475.   superstate = (struct rx_superstate *)rx_cache_get_superstate (cache);
  3476.   if (!superstate)
  3477.     return 0;
  3478.  
  3479.   if (!cache->lru_superstate)
  3480.     (cache->lru_superstate
  3481.      = superstate->next_recyclable
  3482.      = superstate->prev_recyclable
  3483.      = superstate);
  3484.   else
  3485.     {
  3486.       superstate->next_recyclable = cache->lru_superstate;
  3487.       superstate->prev_recyclable = cache->lru_superstate->prev_recyclable;
  3488.       (  superstate->prev_recyclable->next_recyclable
  3489.        = superstate->next_recyclable->prev_recyclable
  3490.        = superstate);
  3491.     }
  3492.   superstate->rx_id = rx->rx_id;
  3493.   superstate->transition_refs = 0;
  3494.   superstate->locks = 0;
  3495.   superstate->is_semifree = 0;
  3496.   set->superstate = superstate;
  3497.   superstate->contents = set;
  3498.   rx_protect_superset (rx, set);
  3499.   superstate->edges = 0;
  3500.   {
  3501.     int x;
  3502.     /* None of the transitions from this superstate are known yet. */
  3503.     for (x = 0; x < rx->local_cset_size; ++x) /* &&&&& 3.8 % */
  3504.       {
  3505.     struct rx_inx * ifr = &superstate->transitions[x];
  3506.     ifr->inx = rx->instruction_table [rx_cache_miss];
  3507.     ifr->data = ifr->data_2 = 0;
  3508.       }
  3509.   }
  3510.   return superstate;
  3511. }
  3512.  
  3513.  
  3514. /* This computes the destination set of one edge of the superstate NFA.
  3515.  * Note that a RX_DISTINCT_FUTURE is a superstate edge.
  3516.  * Returns 0 on an allocation failure.
  3517.  */
  3518.  
  3519. #ifdef __STDC__
  3520. static int 
  3521. solve_destination (struct rx *rx, struct rx_distinct_future *df)
  3522. #else
  3523. static int 
  3524. solve_destination (rx, df)
  3525.      struct rx *rx;
  3526.      struct rx_distinct_future *df;
  3527. #endif
  3528. {
  3529.   struct rx_super_edge *tc = df->edge;
  3530.   struct rx_superset *nfa_state;
  3531.   struct rx_superset *nil_set = rx_superset_cons (rx, 0, 0);
  3532.   struct rx_superset *solution = nil_set;
  3533.   struct rx_superstate *dest;
  3534.  
  3535.   rx_protect_superset (rx, solution);
  3536.   /* Iterate over all NFA states in the state set of this superstate. */
  3537.   for (nfa_state = df->present->contents;
  3538.        nfa_state->car;
  3539.        nfa_state = nfa_state->cdr)
  3540.     {
  3541.       struct rx_nfa_edge *e;
  3542.       /* Iterate over all edges of each NFA state. */
  3543.       for (e = nfa_state->car->edges; e; e = e->next)
  3544.         /* If we find an edge that is labeled with 
  3545.      * the characters we are solving for.....
  3546.      */
  3547.     if (rx_bitset_is_subset (rx->local_cset_size,
  3548.                  tc->cset, e->params.cset))
  3549.       {
  3550.         struct rx_nfa_state *n = e->dest;
  3551.         struct rx_possible_future *pf;
  3552.         /* ....search the partial epsilon closures of the destination
  3553.          * of that edge for a path that involves the same set of
  3554.          * side effects we are solving for.
  3555.          * If we find such a RX_POSSIBLE_FUTURE, we add members to the
  3556.          * stateset we are computing.
  3557.          */
  3558.         for (pf = n->futures; pf; pf = pf->next)
  3559.           if (pf->effects == df->effects)
  3560.         {
  3561.           struct rx_superset * old_sol;
  3562.           old_sol = solution;
  3563.           solution = rx_superstate_eclosure_union (rx, solution,
  3564.                                pf->destset);
  3565.           if (!solution)
  3566.             return 0;
  3567.           rx_protect_superset (rx, solution);
  3568.           rx_release_superset (rx, old_sol);
  3569.         }
  3570.       }
  3571.     }
  3572.   /* It is possible that the RX_DISTINCT_FUTURE we are working on has 
  3573.    * the empty set of NFA states as its definition.  In that case, this
  3574.    * is a failure point.
  3575.    */
  3576.   if (solution == nil_set)
  3577.     {
  3578.       df->future_frame.inx = (void *) rx_backtrack;
  3579.       df->future_frame.data = 0;
  3580.       df->future_frame.data_2 = 0;
  3581.       return 1;
  3582.     }
  3583.   dest = rx_superstate (rx, solution);
  3584.   rx_release_superset (rx, solution);
  3585.   if (!dest)
  3586.     return 0;
  3587.  
  3588.   {
  3589.     struct rx_distinct_future *dft;
  3590.     dft = df;
  3591.     df->prev_same_dest->next_same_dest = 0;
  3592.     while (dft)
  3593.       {
  3594.     dft->future = dest;
  3595.     dft->future_frame.inx = rx->instruction_table[rx_next_char];
  3596.     dft->future_frame.data = (void *) dest->transitions;
  3597.     dft = dft->next_same_dest;
  3598.       }
  3599.     df->prev_same_dest->next_same_dest = df;
  3600.   }
  3601.   if (!dest->transition_refs)
  3602.     dest->transition_refs = df;
  3603.   else
  3604.     {
  3605.       struct rx_distinct_future *dft = dest->transition_refs->next_same_dest;
  3606.       dest->transition_refs->next_same_dest = df->next_same_dest;
  3607.       df->next_same_dest->prev_same_dest = dest->transition_refs;
  3608.       df->next_same_dest = dft;
  3609.       dft->prev_same_dest = df;
  3610.     }
  3611.   return 1;
  3612. }
  3613.  
  3614.  
  3615. /* This takes a superstate and a character, and computes some edges
  3616.  * from the superstate NFA.  In particular, this computes all edges
  3617.  * that lead from SUPERSTATE given CHR.   This function also 
  3618.  * computes the set of characters that share this edge set.
  3619.  * This returns 0 on allocation error.
  3620.  * The character set and list of edges are returned through 
  3621.  * the paramters CSETOUT and DFOUT.
  3622. } */
  3623.  
  3624. #ifdef __STDC__
  3625. static int 
  3626. compute_super_edge (struct rx *rx, struct rx_distinct_future **dfout,
  3627.               rx_Bitset csetout, struct rx_superstate *superstate,
  3628.               unsigned char chr)  
  3629. #else
  3630. static int 
  3631. compute_super_edge (rx, dfout, csetout, superstate, chr)
  3632.      struct rx *rx;
  3633.      struct rx_distinct_future **dfout;
  3634.      rx_Bitset csetout;
  3635.      struct rx_superstate *superstate;
  3636.      unsigned char chr;
  3637. #endif
  3638. {
  3639.   struct rx_superset *stateset = superstate->contents;
  3640.  
  3641.   /* To compute the set of characters that share edges with CHR, 
  3642.    * we start with the full character set, and subtract.
  3643.    */
  3644.   rx_bitset_universe (rx->local_cset_size, csetout);
  3645.   *dfout = 0;
  3646.  
  3647.   /* Iterate over the NFA states in the superstate state-set. */
  3648.   while (stateset->car)
  3649.     {
  3650.       struct rx_nfa_edge *e;
  3651.       for (e = stateset->car->edges; e; e = e->next)
  3652.     if (RX_bitset_member (e->params.cset, chr))
  3653.       {
  3654.         /* If we find an NFA edge that applies, we make sure there
  3655.          * are corresponding edges in the superstate NFA.
  3656.          */
  3657.         {
  3658.           struct rx_distinct_future * saved;
  3659.           saved = *dfout;
  3660.           *dfout = include_futures (rx, *dfout, e->dest, superstate);
  3661.           if (!*dfout)
  3662.         {
  3663.           struct rx_distinct_future * df;
  3664.           df = saved;
  3665.           df->next_same_super_edge[1]->next_same_super_edge[0] = 0;
  3666.           while (df)
  3667.             {
  3668.               struct rx_distinct_future *dft;
  3669.               dft = df;
  3670.               df = df->next_same_super_edge[0];
  3671.  
  3672.               if (dft->future && dft->future->transition_refs == dft)
  3673.             {
  3674.               dft->future->transition_refs = dft->next_same_dest;
  3675.               if (dft->future->transition_refs == dft)
  3676.                 dft->future->transition_refs = 0;
  3677.             }
  3678.               dft->next_same_dest->prev_same_dest = dft->prev_same_dest;
  3679.               dft->prev_same_dest->next_same_dest = dft->next_same_dest;
  3680.               rx_cache_free (rx->cache,
  3681.                      &rx->cache->free_discernable_futures,
  3682.                      (char *)dft);
  3683.             }
  3684.           return 0;
  3685.         }
  3686.         }
  3687.         /* We also trim the character set a bit. */
  3688.         rx_bitset_intersection (rx->local_cset_size,
  3689.                     csetout, e->params.cset);
  3690.       }
  3691.     else
  3692.       /* An edge that doesn't apply at least tells us some characters
  3693.        * that don't share the same edge set as CHR.
  3694.        */
  3695.       rx_bitset_difference (rx->local_cset_size, csetout, e->params.cset);
  3696.       stateset = stateset->cdr;
  3697.     }
  3698.   return 1;
  3699. }
  3700.  
  3701.  
  3702. /* This is a constructor for RX_SUPER_EDGE structures.  These are
  3703.  * wrappers for lists of superstate NFA edges that share character sets labels.
  3704.  * If a transition class contains more than one rx_distinct_future (superstate
  3705.  * edge), then it represents a non-determinism in the superstate NFA.
  3706.  */
  3707.  
  3708. #ifdef __STDC__
  3709. static struct rx_super_edge *
  3710. rx_super_edge (struct rx *rx,
  3711.            struct rx_superstate *super, rx_Bitset cset,
  3712.            struct rx_distinct_future *df) 
  3713. #else
  3714. static struct rx_super_edge *
  3715. rx_super_edge (rx, super, cset, df)
  3716.      struct rx *rx;
  3717.      struct rx_superstate *super;
  3718.      rx_Bitset cset;
  3719.      struct rx_distinct_future *df;
  3720. #endif
  3721. {
  3722.   struct rx_super_edge *tc =
  3723.     (struct rx_super_edge *)rx_cache_malloc_or_get
  3724.       (rx->cache, &rx->cache->free_transition_classes,
  3725.        sizeof (struct rx_super_edge) + rx_sizeof_bitset (rx->local_cset_size));
  3726.  
  3727.   if (!tc)
  3728.     return 0;
  3729.   tc->next = super->edges;
  3730.   super->edges = tc;
  3731.   tc->rx_backtrack_frame.inx = rx->instruction_table[rx_backtrack_point];
  3732.   tc->rx_backtrack_frame.data = 0;
  3733.   tc->rx_backtrack_frame.data_2 = (void *) tc;
  3734.   tc->options = df;
  3735.   tc->cset = (rx_Bitset) ((char *) tc + sizeof (*tc));
  3736.   rx_bitset_assign (rx->local_cset_size, tc->cset, cset);
  3737.   if (df)
  3738.     {
  3739.       struct rx_distinct_future * dfp = df;
  3740.       df->next_same_super_edge[1]->next_same_super_edge[0] = 0;
  3741.       while (dfp)
  3742.     {
  3743.       dfp->edge = tc;
  3744.       dfp = dfp->next_same_super_edge[0];
  3745.     }
  3746.       df->next_same_super_edge[1]->next_same_super_edge[0] = df;
  3747.     }
  3748.   return tc;
  3749. }
  3750.  
  3751.  
  3752. /* There are three kinds of cache miss.  The first occurs when a
  3753.  * transition is taken that has never been computed during the
  3754.  * lifetime of the source superstate.  That cache miss is handled by
  3755.  * calling COMPUTE_SUPER_EDGE.  The second kind of cache miss
  3756.  * occurs when the destination superstate of a transition doesn't
  3757.  * exist.  SOLVE_DESTINATION is used to construct the destination superstate.
  3758.  * Finally, the third kind of cache miss occurs when the destination
  3759.  * superstate of a transition is in a `semi-free state'.  That case is
  3760.  * handled by UNFREE_SUPERSTATE.
  3761.  *
  3762.  * The function of HANDLE_CACHE_MISS is to figure out which of these
  3763.  * cases applies.
  3764.  */
  3765.  
  3766. #ifdef __STDC__
  3767. static void
  3768. install_partial_transition  (struct rx_superstate *super,
  3769.                  struct rx_inx *answer,
  3770.                  RX_subset set, int offset)
  3771. #else
  3772. static void
  3773. install_partial_transition  (super, answer, set, offset)
  3774.      struct rx_superstate *super;
  3775.      struct rx_inx *answer;
  3776.      RX_subset set;
  3777.      int offset;
  3778. #endif
  3779. {
  3780.   int start = offset;
  3781.   int end = start + 32;
  3782.   RX_subset pos = 1;
  3783.   struct rx_inx * transitions = super->transitions;
  3784.   
  3785.   while (start < end)
  3786.     {
  3787.       if (set & pos)
  3788.     transitions[start] = *answer;
  3789.       pos <<= 1;
  3790.       ++start;
  3791.     }
  3792. }
  3793.  
  3794.  
  3795. #ifdef __STDC__
  3796. RX_DECL struct rx_inx *
  3797. rx_handle_cache_miss
  3798.   (struct rx *rx, struct rx_superstate *super, unsigned char chr, void *data) 
  3799. #else
  3800. RX_DECL struct rx_inx *
  3801. rx_handle_cache_miss (rx, super, chr, data)
  3802.      struct rx *rx;
  3803.      struct rx_superstate *super;
  3804.      unsigned char chr;
  3805.      void *data;
  3806. #endif
  3807. {
  3808.   int offset = chr / RX_subset_bits;
  3809.   struct rx_distinct_future *df = data;
  3810.  
  3811.   if (!df)            /* must be the shared_cache_miss_frame */
  3812.     {
  3813.       /* Perhaps this is just a transition waiting to be filled. */
  3814.       struct rx_super_edge *tc;
  3815.       RX_subset mask = rx_subset_singletons [chr % RX_subset_bits];
  3816.  
  3817.       for (tc = super->edges; tc; tc = tc->next)
  3818.     if (tc->cset[offset] & mask)
  3819.       {
  3820.         struct rx_inx * answer;
  3821.         df = tc->options;
  3822.         answer = ((tc->options->next_same_super_edge[0] != tc->options)
  3823.               ? &tc->rx_backtrack_frame
  3824.               : (df->effects
  3825.              ? &df->side_effects_frame
  3826.              : &df->future_frame));
  3827.         install_partial_transition (super, answer,
  3828.                     tc->cset [offset], offset * 32);
  3829.         return answer;
  3830.       }
  3831.       /* Otherwise, it's a flushed or  newly encountered edge. */
  3832.       {
  3833.     char cset_space[1024];    /* this limit is far from unreasonable */
  3834.     rx_Bitset trcset;
  3835.     struct rx_inx *answer;
  3836.  
  3837.     if (rx_sizeof_bitset (rx->local_cset_size) > sizeof (cset_space))
  3838.       return 0;        /* If the arbitrary limit is hit, always fail */
  3839.                 /* cleanly. */
  3840.     trcset = (rx_Bitset)cset_space;
  3841.     rx_lock_superstate (rx, super);
  3842.     if (!compute_super_edge (rx, &df, trcset, super, chr))
  3843.       {
  3844.         rx_unlock_superstate (rx, super);
  3845.         return 0;
  3846.       }
  3847.     if (!df)        /* We just computed the fail transition. */
  3848.       {
  3849.         static struct rx_inx
  3850.           shared_fail_frame = { (void *)rx_backtrack, 0, 0 };
  3851.         answer = &shared_fail_frame;
  3852.       }
  3853.     else
  3854.       {
  3855.         tc = rx_super_edge (rx, super, trcset, df);
  3856.         if (!tc)
  3857.           {
  3858.         rx_unlock_superstate (rx, super);
  3859.         return 0;
  3860.           }
  3861.         answer = ((tc->options->next_same_super_edge[0] != tc->options)
  3862.               ? &tc->rx_backtrack_frame
  3863.               : (df->effects
  3864.              ? &df->side_effects_frame
  3865.              : &df->future_frame));
  3866.       }
  3867.     install_partial_transition (super, answer,
  3868.                     trcset[offset], offset * 32);
  3869.     rx_unlock_superstate (rx, super);
  3870.     return answer;
  3871.       }
  3872.     }
  3873.   else if (df->future) /* A cache miss on an edge with a future? Must be
  3874.             * a semi-free destination. */
  3875.     {                
  3876.       if (df->future->is_semifree)
  3877.     refresh_semifree_superstate (rx->cache, df->future);
  3878.       return &df->future_frame;
  3879.     }
  3880.   else
  3881.     /* no future superstate on an existing edge */
  3882.     {
  3883.       rx_lock_superstate (rx, super);
  3884.       if (!solve_destination (rx, df))
  3885.     {
  3886.       rx_unlock_superstate (rx, super);
  3887.       return 0;
  3888.     }
  3889.       if (!df->effects
  3890.       && (df->edge->options->next_same_super_edge[0] == df->edge->options))
  3891.     install_partial_transition (super, &df->future_frame,
  3892.                     df->edge->cset[offset], offset * 32);
  3893.       rx_unlock_superstate (rx, super);
  3894.       return &df->future_frame;
  3895.     }
  3896. }
  3897.  
  3898.  
  3899.  
  3900.  
  3901. /* The rest of the code provides a regex.c compatable interface. */
  3902.  
  3903.  
  3904. __const__ char *re_error_msg[] =
  3905. {
  3906.   0,                        /* REG_NOUT */
  3907.   "No match",                    /* REG_NOMATCH */
  3908.   "Invalid regular expression",            /* REG_BADPAT */
  3909.   "Invalid collation character",        /* REG_ECOLLATE */
  3910.   "Invalid character class name",        /* REG_ECTYPE */
  3911.   "Trailing backslash",                /* REG_EESCAPE */
  3912.   "Invalid back reference",            /* REG_ESUBREG */
  3913.   "Unmatched [ or [^",                /* REG_EBRACK */
  3914.   "Unmatched ( or \\(",                /* REG_EPAREN */
  3915.   "Unmatched \\{",                /* REG_EBRACE */
  3916.   "Invalid content of \\{\\}",            /* REG_BADBR */
  3917.   "Invalid range end",                /* REG_ERANGE */
  3918.   "Memory exhausted",                /* REG_ESPACE */
  3919.   "Invalid preceding regular expression",    /* REG_BADRPT */
  3920.   "Premature end of regular expression",    /* REG_EEND */
  3921.   "Regular expression too big",            /* REG_ESIZE */
  3922.   "Unmatched ) or \\)",                /* REG_ERPAREN */
  3923. };
  3924.  
  3925.  
  3926.  
  3927. /* 
  3928.  * Macros used while compiling patterns.
  3929.  *
  3930.  * By convention, PEND points just past the end of the uncompiled pattern,
  3931.  * P points to the read position in the pattern.  `translate' is the name
  3932.  * of the translation table (`TRANSLATE' is the name of a macro that looks
  3933.  * things up in `translate').
  3934.  */
  3935.  
  3936.  
  3937. /*
  3938.  * Fetch the next character in the uncompiled pattern---translating it 
  3939.  * if necessary. *Also cast from a signed character in the constant
  3940.  * string passed to us by the user to an unsigned char that we can use
  3941.  * as an array index (in, e.g., `translate').
  3942.  */
  3943. #define PATFETCH(c)                            \
  3944.  do {if (p == pend) return REG_EEND;                    \
  3945.     c = (unsigned char) *p++;                        \
  3946.     c = translate[c];                             \
  3947.  } while (0)
  3948.  
  3949. /* 
  3950.  * Fetch the next character in the uncompiled pattern, with no
  3951.  * translation.
  3952.  */
  3953. #define PATFETCH_RAW(c)                            \
  3954.   do {if (p == pend) return REG_EEND;                    \
  3955.     c = (unsigned char) *p++;                         \
  3956.   } while (0)
  3957.  
  3958. /* Go backwards one character in the pattern.  */
  3959. #define PATUNFETCH p--
  3960.  
  3961.  
  3962. #define TRANSLATE(d) translate[(unsigned char) (d)]
  3963.  
  3964. typedef unsigned regnum_t;
  3965.  
  3966. /* Since offsets can go either forwards or backwards, this type needs to
  3967.  * be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1.
  3968.  */
  3969. typedef int pattern_offset_t;
  3970.  
  3971. typedef struct
  3972. {
  3973.   struct rexp_node ** top_expression; /* was begalt */
  3974.   struct rexp_node ** last_expression; /* was laststart */
  3975.   pattern_offset_t inner_group_offset;
  3976.   regnum_t regnum;
  3977. } compile_stack_elt_t;
  3978.  
  3979. typedef struct
  3980. {
  3981.   compile_stack_elt_t *stack;
  3982.   unsigned size;
  3983.   unsigned avail;            /* Offset of next open position.  */
  3984. } compile_stack_type;
  3985.  
  3986.  
  3987. #define INIT_COMPILE_STACK_SIZE 32
  3988.  
  3989. #define COMPILE_STACK_EMPTY  (compile_stack.avail == 0)
  3990. #define COMPILE_STACK_FULL  (compile_stack.avail == compile_stack.size)
  3991.  
  3992. /* The next available element.  */
  3993. #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
  3994.  
  3995.  
  3996. /* Set the bit for character C in a list.  */
  3997. #define SET_LIST_BIT(c)                               \
  3998.   (b[((unsigned char) (c)) / CHARBITS]               \
  3999.    |= 1 << (((unsigned char) c) % CHARBITS))
  4000.  
  4001. /* Get the next unsigned number in the uncompiled pattern.  */
  4002. #define GET_UNSIGNED_NUMBER(num)                     \
  4003.   { if (p != pend)                            \
  4004.      {                                    \
  4005.        PATFETCH (c);                             \
  4006.        while (isdigit (c))                         \
  4007.          {                                 \
  4008.            if (num < 0)                            \
  4009.               num = 0;                            \
  4010.            num = num * 10 + c - '0';                     \
  4011.            if (p == pend)                         \
  4012.               break;                             \
  4013.            PATFETCH (c);                        \
  4014.          }                                 \
  4015.        }                                 \
  4016.     }        
  4017.  
  4018. #define CHAR_CLASS_MAX_LENGTH  6 /* Namely, `xdigit'.  */
  4019.  
  4020. #define IS_CHAR_CLASS(string)                        \
  4021.    (!strcmp (string, "alpha") || !strcmp (string, "upper")        \
  4022.     || !strcmp (string, "lower") || !strcmp (string, "digit")        \
  4023.     || !strcmp (string, "alnum") || !strcmp (string, "xdigit")        \
  4024.     || !strcmp (string, "space") || !strcmp (string, "print")        \
  4025.     || !strcmp (string, "punct") || !strcmp (string, "graph")        \
  4026.     || !strcmp (string, "cntrl") || !strcmp (string, "blank"))
  4027.  
  4028.  
  4029. /* These predicates are used in regex_compile. */
  4030.  
  4031. /* P points to just after a ^ in PATTERN.  Return true if that ^ comes
  4032.  * after an alternative or a begin-subexpression.  We assume there is at
  4033.  * least one character before the ^.  
  4034.  */
  4035.  
  4036. #ifdef __STDC__
  4037. static boolean
  4038. at_begline_loc_p (__const__ char *pattern, __const__ char * p, reg_syntax_t syntax)
  4039. #else
  4040. static boolean
  4041. at_begline_loc_p (pattern, p, syntax)
  4042.      __const__ char *pattern;
  4043.      __const__ char * p;
  4044.      reg_syntax_t syntax;
  4045. #endif
  4046. {
  4047.   __const__ char *prev = p - 2;
  4048.   boolean prev_prev_backslash = ((prev > pattern) && (prev[-1] == '\\'));
  4049.   
  4050.     return
  4051.       
  4052.       (/* After a subexpression?  */
  4053.        ((*prev == '(') && ((syntax & RE_NO_BK_PARENS) || prev_prev_backslash))
  4054.        ||
  4055.        /* After an alternative?  */
  4056.        ((*prev == '|') && ((syntax & RE_NO_BK_VBAR) || prev_prev_backslash))
  4057.        );
  4058. }
  4059.  
  4060. /* The dual of at_begline_loc_p.  This one is for $.  We assume there is
  4061.  * at least one character after the $, i.e., `P < PEND'.
  4062.  */
  4063.  
  4064. #ifdef __STDC__
  4065. static boolean
  4066. at_endline_loc_p (__const__ char *p, __const__ char *pend, int syntax)
  4067. #else
  4068. static boolean
  4069. at_endline_loc_p (p, pend, syntax)
  4070.      __const__ char *p;
  4071.      __const__ char *pend;
  4072.      int syntax;
  4073. #endif
  4074. {
  4075.   __const__ char *next = p;
  4076.   boolean next_backslash = (*next == '\\');
  4077.   __const__ char *next_next = (p + 1 < pend) ? (p + 1) : 0;
  4078.   
  4079.   return
  4080.     (
  4081.      /* Before a subexpression?  */
  4082.      ((syntax & RE_NO_BK_PARENS)
  4083.       ? (*next == ')')
  4084.       : (next_backslash && next_next && (*next_next == ')')))
  4085.     ||
  4086.      /* Before an alternative?  */
  4087.      ((syntax & RE_NO_BK_VBAR)
  4088.       ? (*next == '|')
  4089.       : (next_backslash && next_next && (*next_next == '|')))
  4090.      );
  4091. }
  4092.  
  4093.  
  4094. unsigned char rx_id_translation[256] =
  4095. {
  4096.   0,  1,  2,  3,  4,  5,  6,  7,  8,  9,
  4097.  10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
  4098.  20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  4099.  30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
  4100.  40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
  4101.  50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  4102.  60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
  4103.  70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
  4104.  80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
  4105.  90, 91, 92, 93, 94, 95, 96, 97, 98, 99,
  4106.  
  4107.  100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
  4108.  110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  4109.  120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
  4110.  130, 131, 132, 133, 134, 135, 136, 137, 138, 139,
  4111.  140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  4112.  150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
  4113.  160, 161, 162, 163, 164, 165, 166, 167, 168, 169,
  4114.  170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  4115.  180, 181, 182, 183, 184, 185, 186, 187, 188, 189,
  4116.  190, 191, 192, 193, 194, 195, 196, 197, 198, 199,
  4117.  
  4118.  200, 201, 202, 203, 204, 205, 206, 207, 208, 209,
  4119.  210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
  4120.  220, 221, 222, 223, 224, 225, 226, 227, 228, 229,
  4121.  230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  4122.  240, 241, 242, 243, 244, 245, 246, 247, 248, 249,
  4123.  250, 251, 252, 253, 254, 255
  4124. };
  4125.  
  4126. /* The compiler keeps an inverted translation table.
  4127.  * This looks up/inititalize elements.
  4128.  * VALID is an array of booleans that validate CACHE.
  4129.  */
  4130.  
  4131. #ifdef __STDC__
  4132. static rx_Bitset
  4133. inverse_translation (struct re_pattern_buffer * rxb,
  4134.              char * valid, rx_Bitset cache,
  4135.              unsigned char * translate, int c)
  4136. #else
  4137. static rx_Bitset
  4138. inverse_translation (rxb, valid, cache, translate, c)
  4139.      struct re_pattern_buffer * rxb;
  4140.      char * valid;
  4141.      rx_Bitset cache;
  4142.      unsigned char * translate;
  4143.      int c;
  4144. #endif
  4145. {
  4146.   rx_Bitset cs
  4147.     = cache + c * rx_bitset_numb_subsets (rxb->rx.local_cset_size); 
  4148.  
  4149.   if (!valid[c])
  4150.     {
  4151.       int x;
  4152.       int c_tr = TRANSLATE(c);
  4153.       rx_bitset_null (rxb->rx.local_cset_size, cs);
  4154.       for (x = 0; x < 256; ++x)    /* &&&& 13.37 */
  4155.     if (TRANSLATE(x) == c_tr)
  4156.       RX_bitset_enjoin (cs, x);
  4157.       valid[c] = 1;
  4158.     }
  4159.   return cs;
  4160. }
  4161.  
  4162.  
  4163.  
  4164.  
  4165. /* More subroutine declarations and macros for regex_compile.  */
  4166.  
  4167. /* Returns true if REGNUM is in one of COMPILE_STACK's elements and 
  4168.    false if it's not.  */
  4169.  
  4170. #ifdef __STDC__
  4171. static boolean
  4172. group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
  4173. #else
  4174. static boolean
  4175. group_in_compile_stack (compile_stack, regnum)
  4176.     compile_stack_type compile_stack;
  4177.     regnum_t regnum;
  4178. #endif
  4179. {
  4180.   int this_element;
  4181.  
  4182.   for (this_element = compile_stack.avail - 1;  
  4183.        this_element >= 0; 
  4184.        this_element--)
  4185.     if (compile_stack.stack[this_element].regnum == regnum)
  4186.       return true;
  4187.  
  4188.   return false;
  4189. }
  4190.  
  4191.  
  4192. /*
  4193.  * Read the ending character of a range (in a bracket expression) from the
  4194.  * uncompiled pattern *P_PTR (which ends at PEND).  We assume the
  4195.  * starting character is in `P[-2]'.  (`P[-1]' is the character `-'.)
  4196.  * Then we set the translation of all bits between the starting and
  4197.  * ending characters (inclusive) in the compiled pattern B.
  4198.  * 
  4199.  * Return an error code.
  4200.  * 
  4201.  * We use these short variable names so we can use the same macros as
  4202.  * `regex_compile' itself.  
  4203.  */
  4204.  
  4205. #ifdef __STDC__
  4206. static reg_errcode_t
  4207. compile_range (struct re_pattern_buffer * rxb, rx_Bitset cs,
  4208.            __const__ char ** p_ptr, __const__ char * pend,
  4209.            unsigned char * translate, reg_syntax_t syntax,
  4210.            rx_Bitset inv_tr,  char * valid_inv_tr)
  4211. #else
  4212. static reg_errcode_t
  4213. compile_range (rxb, cs, p_ptr, pend, translate, syntax, inv_tr, valid_inv_tr)
  4214.      struct re_pattern_buffer * rxb;
  4215.      rx_Bitset cs;
  4216.      __const__ char ** p_ptr;
  4217.      __const__ char * pend;
  4218.      unsigned char * translate;
  4219.      reg_syntax_t syntax;
  4220.      rx_Bitset inv_tr;
  4221.      char * valid_inv_tr;
  4222. #endif
  4223. {
  4224.   unsigned this_char;
  4225.  
  4226.   __const__ char *p = *p_ptr;
  4227.  
  4228.   unsigned char range_end;
  4229.   unsigned char range_start = TRANSLATE(p[-2]);
  4230.  
  4231.   if (p == pend)
  4232.     return REG_ERANGE;
  4233.  
  4234.   PATFETCH (range_end);
  4235.  
  4236.   (*p_ptr)++;
  4237.  
  4238.   if (range_start > range_end)
  4239.     return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
  4240.  
  4241.   for (this_char = range_start; this_char <= range_end; this_char++)
  4242.     {
  4243.       rx_Bitset it =
  4244.     inverse_translation (rxb, valid_inv_tr, inv_tr, translate, this_char);
  4245.       rx_bitset_union (rxb->rx.local_cset_size, cs, it);
  4246.     }
  4247.   
  4248.   return REG_NOERROR;
  4249. }
  4250.  
  4251.  
  4252. /* This searches a regexp for backreference side effects.
  4253.  * It fills in the array OUT with 1 at the index of every register pair
  4254.  * referenced by a backreference.
  4255.  *
  4256.  * This is used to help optimize patterns for searching.  The information is
  4257.  * useful because, if the caller doesn't want register values, backreferenced
  4258.  * registers are the only registers for which we need rx_backtrack.
  4259.  */
  4260.  
  4261. #ifdef __STDC__
  4262. static void
  4263. find_backrefs (char * out, struct rexp_node * rexp,
  4264.            struct re_se_params * params)
  4265. #else
  4266. static void
  4267. find_backrefs (out, rexp, params)
  4268.      char * out;
  4269.      struct rexp_node * rexp;
  4270.      struct re_se_params * params;
  4271. #endif
  4272. {
  4273.   if (rexp)
  4274.     switch (rexp->type)
  4275.       {
  4276.       case r_cset:
  4277.       case r_data:
  4278.     return;
  4279.       case r_alternate:
  4280.       case r_concat:
  4281.       case r_opt:
  4282.       case r_star:
  4283.       case r_2phase_star:
  4284.     find_backrefs (out, rexp->params.pair.left, params);
  4285.     find_backrefs (out, rexp->params.pair.right, params);
  4286.     return;
  4287.       case r_side_effect:
  4288.     if (   ((long)rexp->params.side_effect >= 0)
  4289.         && (params [(long)rexp->params.side_effect].se == re_se_backref))
  4290.       out[ params [(long)rexp->params.side_effect].op1] = 1;
  4291.     return;
  4292.       }
  4293. }
  4294.  
  4295.  
  4296.  
  4297. /* Returns 0 unless the pattern can match the empty string. */
  4298.  
  4299. #ifdef __STDC__
  4300. static int
  4301. compute_fastset (struct re_pattern_buffer * rxb, struct rexp_node * rexp)
  4302. #else
  4303. static int
  4304. compute_fastset (rxb, rexp)
  4305.      struct re_pattern_buffer * rxb;
  4306.      struct rexp_node * rexp;
  4307. #endif
  4308. {
  4309.   if (!rexp)
  4310.     return 1;
  4311.   switch (rexp->type)
  4312.     {
  4313.     case r_data:
  4314.       return 1;
  4315.     case r_cset:
  4316.       {
  4317.     rx_bitset_union (rxb->rx.local_cset_size,
  4318.              rxb->fastset, rexp->params.cset);
  4319.       }
  4320.       return 0;
  4321.     case r_concat:
  4322.       return (compute_fastset (rxb, rexp->params.pair.left)
  4323.           && compute_fastset (rxb, rexp->params.pair.right));
  4324.     case r_2phase_star:
  4325.       compute_fastset (rxb, rexp->params.pair.left);
  4326.       /* compute_fastset (rxb, rexp->params.pair.right);  nope... */
  4327.       return 1;
  4328.     case r_alternate:
  4329.       return !!(compute_fastset (rxb, rexp->params.pair.left)
  4330.         + compute_fastset (rxb, rexp->params.pair.right));
  4331.     case r_opt:
  4332.     case r_star:
  4333.       compute_fastset (rxb, rexp->params.pair.left);
  4334.       return 1;
  4335.     case r_side_effect:
  4336.       return 1;
  4337.     }
  4338.  
  4339.   /* this should never happen */
  4340.   return 0;
  4341. }
  4342.  
  4343.  
  4344. /* returns
  4345.  *  1 -- yes, definately anchored by the given side effect.
  4346.  *  2 -- maybe anchored, maybe the empty string.
  4347.  *  0 -- definately not anchored
  4348.  *  There is simply no other possibility.
  4349.  */
  4350.  
  4351. #ifdef __STDC__
  4352. static int
  4353. is_anchored (struct rexp_node * rexp, rx_side_effect se)
  4354. #else
  4355. static int
  4356. is_anchored (rexp, se)
  4357.      struct rexp_node * rexp;
  4358.      rx_side_effect se;
  4359. #endif
  4360. {
  4361.   if (!rexp)
  4362.     return 2;
  4363.   switch (rexp->type)
  4364.     {
  4365.     case r_cset:
  4366.     case r_data:
  4367.       return 0;
  4368.     case r_concat:
  4369.     case r_2phase_star:
  4370.       {
  4371.     int l = is_anchored (rexp->params.pair.left, se);
  4372.     return (l == 2 ? is_anchored (rexp->params.pair.right, se) : l);
  4373.       }
  4374.     case r_alternate:
  4375.       {
  4376.     int l = is_anchored (rexp->params.pair.left, se);
  4377.     int r = l ? is_anchored (rexp->params.pair.right, se) : 0;
  4378.     return MAX (l, r);
  4379.       }
  4380.     case r_opt:
  4381.     case r_star:
  4382.       return is_anchored (rexp->params.pair.left, se) ? 2 : 0;
  4383.       
  4384.     case r_side_effect:
  4385.       return ((rexp->params.side_effect == se)
  4386.           ? 1 : 2);
  4387.     }
  4388.  
  4389.   /* this should never happen */
  4390.   return 0;
  4391. }
  4392.  
  4393.  
  4394. /* This removes register assignments that aren't required by backreferencing.
  4395.  * This can speed up explore_future, especially if it eliminates
  4396.  * non-determinism in the superstate NFA.
  4397.  * 
  4398.  * NEEDED is an array of characters, presumably filled in by FIND_BACKREFS.
  4399.  * The non-zero elements of the array indicate which register assignments
  4400.  * can NOT be removed from the expression.
  4401.  */
  4402.  
  4403. #ifdef __STDC__
  4404. static struct rexp_node *
  4405. remove_unecessary_side_effects (struct rx * rx, char * needed,
  4406.                 struct rexp_node * rexp,
  4407.                 struct re_se_params * params)
  4408. #else
  4409. static struct rexp_node *
  4410. remove_unecessary_side_effects (rx, needed, rexp, params)
  4411.      struct rx * rx;
  4412.      char * needed;
  4413.      struct rexp_node * rexp;
  4414.      struct re_se_params * params;
  4415. #endif
  4416. {
  4417.   struct rexp_node * l;
  4418.   struct rexp_node * r;
  4419.   if (!rexp)
  4420.     return 0;
  4421.   else
  4422.     switch (rexp->type)
  4423.       {
  4424.       case r_cset:
  4425.       case r_data:
  4426.     return rexp;
  4427.       case r_alternate:
  4428.       case r_concat:
  4429.       case r_2phase_star:
  4430.     l = remove_unecessary_side_effects (rx, needed,
  4431.                         rexp->params.pair.left, params);
  4432.     r = remove_unecessary_side_effects (rx, needed,
  4433.                         rexp->params.pair.right, params);
  4434.     if ((l && r) || (rexp->type != r_concat))
  4435.       {
  4436.         rexp->params.pair.left = l;
  4437.         rexp->params.pair.right = r;
  4438.         return rexp;
  4439.       }
  4440.     else
  4441.       {
  4442.         rexp->params.pair.left = rexp->params.pair.right = 0;
  4443.         rx_free_rexp (rx, rexp);
  4444.         return l ? l : r;
  4445.       }
  4446.       case r_opt:
  4447.       case r_star:
  4448.     l = remove_unecessary_side_effects (rx, needed,
  4449.                         rexp->params.pair.left, params);
  4450.     if (l)
  4451.       {
  4452.         rexp->params.pair.left = l;
  4453.         return rexp;
  4454.       }
  4455.     else
  4456.       {
  4457.         rexp->params.pair.left = 0;
  4458.         rx_free_rexp (rx, rexp);
  4459.         return 0;
  4460.       }
  4461.       case r_side_effect:
  4462.     {
  4463.       int se = (long)rexp->params.side_effect;
  4464.       if (   (se >= 0)
  4465.           && (   ((enum re_side_effects)params[se].se == re_se_lparen)
  4466.           || ((enum re_side_effects)params[se].se == re_se_rparen))
  4467.           && (params [se].op1 > 0)
  4468.           && (!needed [params [se].op1]))
  4469.         {
  4470.           rx_free_rexp (rx, rexp);
  4471.           return 0;
  4472.         }
  4473.       else
  4474.         return rexp;
  4475.     }
  4476.       }
  4477.  
  4478.   /* this should never happen */
  4479.   return 0;
  4480. }
  4481.  
  4482.  
  4483.  
  4484. #ifdef __STDC__
  4485. static int
  4486. pointless_if_repeated (struct rexp_node * node, struct re_se_params * params)
  4487. #else
  4488. static int
  4489. pointless_if_repeated (node, params)
  4490.      struct rexp_node * node;
  4491.      struct re_se_params * params;
  4492. #endif
  4493. {
  4494.   if (!node)
  4495.     return 1;
  4496.   switch (node->type)
  4497.     {
  4498.     case r_cset:
  4499.       return 0;
  4500.     case r_alternate:
  4501.     case r_concat:
  4502.     case r_2phase_star:
  4503.       return (pointless_if_repeated (node->params.pair.left, params)
  4504.           && pointless_if_repeated (node->params.pair.right, params));
  4505.     case r_opt:
  4506.     case r_star:
  4507.       return pointless_if_repeated (node->params.pair.left, params);
  4508.     case r_side_effect:
  4509.       switch (((long)node->params.side_effect < 0)
  4510.           ? (enum re_side_effects)node->params.side_effect
  4511.           : (enum re_side_effects)params[(long)node->params.side_effect].se)
  4512.     {
  4513.     case re_se_try:
  4514.     case re_se_at_dot:
  4515.     case re_se_begbuf:
  4516.     case re_se_hat:
  4517.     case re_se_wordbeg:
  4518.     case re_se_wordbound:
  4519.     case re_se_notwordbound:
  4520.     case re_se_wordend:
  4521.     case re_se_endbuf:
  4522.     case re_se_dollar:
  4523.     case re_se_fail:
  4524.     case re_se_win:
  4525.       return 1;
  4526.     case re_se_lparen:
  4527.     case re_se_rparen:
  4528.     case re_se_iter:
  4529.     case re_se_end_iter:
  4530.     case re_se_syntax:
  4531.     case re_se_not_syntax:
  4532.     case re_se_backref:
  4533.       return 0;
  4534.     }
  4535.     case r_data:
  4536.     default:
  4537.       return 0;
  4538.     }
  4539. }
  4540.  
  4541.  
  4542.  
  4543. #ifdef __STDC__
  4544. static int
  4545. registers_on_stack (struct re_pattern_buffer * rxb,
  4546.             struct rexp_node * rexp, int in_danger,
  4547.             struct re_se_params * params)
  4548. #else
  4549. static int
  4550. registers_on_stack (rxb, rexp, in_danger, params)
  4551.      struct re_pattern_buffer * rxb;
  4552.      struct rexp_node * rexp;
  4553.      int in_danger;
  4554.      struct re_se_params * params;
  4555. #endif
  4556. {
  4557.   if (!rexp)
  4558.     return 0;
  4559.   else
  4560.     switch (rexp->type)
  4561.       {
  4562.       case r_cset:
  4563.       case r_data:
  4564.     return 0;
  4565.       case r_alternate:
  4566.       case r_concat:
  4567.     return (   registers_on_stack (rxb, rexp->params.pair.left,
  4568.                        in_danger, params)
  4569.         || (registers_on_stack
  4570.             (rxb, rexp->params.pair.right,
  4571.              in_danger, params)));
  4572.       case r_opt:
  4573.     return registers_on_stack (rxb, rexp->params.pair.left, 0, params);
  4574.       case r_star:
  4575.     return registers_on_stack (rxb, rexp->params.pair.left, 1, params);
  4576.       case r_2phase_star:
  4577.     return
  4578.       (   registers_on_stack (rxb, rexp->params.pair.left, 1, params)
  4579.        || registers_on_stack (rxb, rexp->params.pair.right, 1, params));
  4580.       case r_side_effect:
  4581.     {
  4582.       int se = (long)rexp->params.side_effect;
  4583.       if (   in_danger
  4584.           && (se >= 0)
  4585.           && (params [se].op1 > 0)
  4586.           && (   ((enum re_side_effects)params[se].se == re_se_lparen)
  4587.           || ((enum re_side_effects)params[se].se == re_se_rparen)))
  4588.         return 1;
  4589.       else
  4590.         return 0;
  4591.     }
  4592.       }
  4593.  
  4594.   /* this should never happen */
  4595.   return 0;
  4596. }
  4597.  
  4598.  
  4599.  
  4600. static char idempotent_complex_se[] =
  4601. {
  4602. #define RX_WANT_SE_DEFS 1
  4603. #undef RX_DEF_SE
  4604. #undef RX_DEF_CPLX_SE
  4605. #define RX_DEF_SE(IDEM, NAME, VALUE)          
  4606. #define RX_DEF_CPLX_SE(IDEM, NAME, VALUE)     IDEM,
  4607. #include "rx.h"
  4608. #undef RX_DEF_SE
  4609. #undef RX_DEF_CPLX_SE
  4610. #undef RX_WANT_SE_DEFS
  4611.   23
  4612. };
  4613.  
  4614. static char idempotent_se[] =
  4615. {
  4616.   13,
  4617. #define RX_WANT_SE_DEFS 1
  4618. #undef RX_DEF_SE
  4619. #undef RX_DEF_CPLX_SE
  4620. #define RX_DEF_SE(IDEM, NAME, VALUE)          IDEM,
  4621. #define RX_DEF_CPLX_SE(IDEM, NAME, VALUE)     
  4622. #include "rx.h"
  4623. #undef RX_DEF_SE
  4624. #undef RX_DEF_CPLX_SE
  4625. #undef RX_WANT_SE_DEFS
  4626.   42
  4627. };
  4628.  
  4629.  
  4630.  
  4631.  
  4632. #ifdef __STDC__
  4633. static int
  4634. has_any_se (struct rx * rx,
  4635.         struct rexp_node * rexp)
  4636. #else
  4637. static int
  4638. has_any_se (rx, rexp)
  4639.      struct rx * rx;
  4640.      struct rexp_node * rexp;
  4641. #endif
  4642. {
  4643.   if (!rexp)
  4644.     return 0;
  4645.  
  4646.   switch (rexp->type)
  4647.     {
  4648.     case r_cset:
  4649.     case r_data:
  4650.       return 0;
  4651.  
  4652.     case r_side_effect:
  4653.       return 1;
  4654.       
  4655.     case r_2phase_star:
  4656.     case r_concat:
  4657.     case r_alternate:
  4658.       return
  4659.     (   has_any_se (rx, rexp->params.pair.left)
  4660.      || has_any_se (rx, rexp->params.pair.right));
  4661.  
  4662.     case r_opt:
  4663.     case r_star:
  4664.       return has_any_se (rx, rexp->params.pair.left);
  4665.     }
  4666.  
  4667.   /* this should never happen */
  4668.   return 0;
  4669. }
  4670.  
  4671.  
  4672.  
  4673. /* This must be called AFTER `convert_hard_loops' for a given REXP. */
  4674. #ifdef __STDC__
  4675. static int
  4676. has_non_idempotent_epsilon_path (struct rx * rx,
  4677.                  struct rexp_node * rexp,
  4678.                  struct re_se_params * params)
  4679. #else
  4680. static int
  4681. has_non_idempotent_epsilon_path (rx, rexp, params)
  4682.      struct rx * rx;
  4683.      struct rexp_node * rexp;
  4684.      struct re_se_params * params;
  4685. #endif
  4686. {
  4687.   if (!rexp)
  4688.     return 0;
  4689.  
  4690.   switch (rexp->type)
  4691.     {
  4692.     case r_cset:
  4693.     case r_data:
  4694.     case r_star:
  4695.       return 0;
  4696.  
  4697.     case r_side_effect:
  4698.       return
  4699.     !((long)rexp->params.side_effect > 0
  4700.       ? idempotent_complex_se [ params [(long)rexp->params.side_effect].se ]
  4701.       : idempotent_se [-(long)rexp->params.side_effect]);
  4702.       
  4703.     case r_alternate:
  4704.       return
  4705.     (   has_non_idempotent_epsilon_path (rx,
  4706.                          rexp->params.pair.left, params)
  4707.      || has_non_idempotent_epsilon_path (rx,
  4708.                          rexp->params.pair.right, params));
  4709.  
  4710.     case r_2phase_star:
  4711.     case r_concat:
  4712.       return
  4713.     (   has_non_idempotent_epsilon_path (rx,
  4714.                          rexp->params.pair.left, params)
  4715.      && has_non_idempotent_epsilon_path (rx,
  4716.                          rexp->params.pair.right, params));
  4717.  
  4718.     case r_opt:
  4719.       return has_non_idempotent_epsilon_path (rx,
  4720.                           rexp->params.pair.left, params);
  4721.     }
  4722.  
  4723.   /* this should never happen */
  4724.   return 0;
  4725. }
  4726.  
  4727.  
  4728.  
  4729. /* This computes rougly what it's name suggests.   It can (and does) go wrong 
  4730.  * in the direction of returning spurious 0 without causing disasters.
  4731.  */
  4732. #ifdef __STDC__
  4733. static int
  4734. begins_with_complex_se (struct rx * rx, struct rexp_node * rexp)
  4735. #else
  4736. static int
  4737. begins_with_complex_se (rx, rexp)
  4738.      struct rx * rx;
  4739.      struct rexp_node * rexp;
  4740. #endif
  4741. {
  4742.   if (!rexp)
  4743.     return 0;
  4744.  
  4745.   switch (rexp->type)
  4746.     {
  4747.     case r_cset:
  4748.     case r_data:
  4749.       return 0;
  4750.  
  4751.     case r_side_effect:
  4752.       return ((long)rexp->params.side_effect >= 0);
  4753.       
  4754.     case r_alternate:
  4755.       return
  4756.     (   begins_with_complex_se (rx, rexp->params.pair.left)
  4757.      && begins_with_complex_se (rx, rexp->params.pair.right));
  4758.  
  4759.  
  4760.     case r_concat:
  4761.       return has_any_se (rx, rexp->params.pair.left);
  4762.     case r_opt:
  4763.     case r_star:
  4764.     case r_2phase_star:
  4765.       return 0;
  4766.     }
  4767.  
  4768.   /* this should never happen */
  4769.   return 0;
  4770. }
  4771.  
  4772.  
  4773. /* This destructively removes some of the re_se_tv side effects from 
  4774.  * a rexp tree.  In particular, during parsing re_se_tv was inserted on the
  4775.  * right half of every | to guarantee that posix path preference could be 
  4776.  * honored.  This function removes some which it can be determined aren't 
  4777.  * needed.  
  4778.  */
  4779.  
  4780. #ifdef __STDC__
  4781. static void
  4782. speed_up_alt (struct rx * rx,
  4783.           struct rexp_node * rexp,
  4784.           int unposix)
  4785. #else
  4786. static void
  4787. speed_up_alt (rx, rexp, unposix)
  4788.      struct rx * rx;
  4789.      struct rexp_node * rexp;
  4790.      int unposix;
  4791. #endif
  4792. {
  4793.   if (!rexp)
  4794.     return;
  4795.  
  4796.   switch (rexp->type)
  4797.     {
  4798.     case r_cset:
  4799.     case r_data:
  4800.     case r_side_effect:
  4801.       return;
  4802.  
  4803.     case r_opt:
  4804.     case r_star:
  4805.       speed_up_alt (rx, rexp->params.pair.left, unposix);
  4806.       return;
  4807.  
  4808.     case r_2phase_star:
  4809.     case r_concat:
  4810.       speed_up_alt (rx, rexp->params.pair.left, unposix);
  4811.       speed_up_alt (rx, rexp->params.pair.right, unposix);
  4812.       return;
  4813.  
  4814.     case r_alternate:
  4815.       /* the right child is guaranteed to be (concat re_se_tv <subexp>) */
  4816.  
  4817.       speed_up_alt (rx, rexp->params.pair.left, unposix);
  4818.       speed_up_alt (rx, rexp->params.pair.right->params.pair.right, unposix);
  4819.       
  4820.       if (   unposix
  4821.       || (begins_with_complex_se
  4822.           (rx, rexp->params.pair.right->params.pair.right))
  4823.       || !(   has_any_se (rx, rexp->params.pair.right->params.pair.right)
  4824.            || has_any_se (rx, rexp->params.pair.left)))
  4825.     {
  4826.       struct rexp_node * conc = rexp->params.pair.right;
  4827.       rexp->params.pair.right = conc->params.pair.right;
  4828.       conc->params.pair.right = 0;
  4829.       rx_free_rexp (rx, conc);
  4830.     }
  4831.     }
  4832. }
  4833.  
  4834.  
  4835.  
  4836.  
  4837.  
  4838. /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
  4839.    Returns one of error codes defined in `regex.h', or zero for success.
  4840.  
  4841.    Assumes the `allocated' (and perhaps `buffer') and `translate'
  4842.    fields are set in BUFP on entry.
  4843.  
  4844.    If it succeeds, results are put in BUFP (if it returns an error, the
  4845.    contents of BUFP are undefined):
  4846.      `buffer' is the compiled pattern;
  4847.      `syntax' is set to SYNTAX;
  4848.      `used' is set to the length of the compiled pattern;
  4849.      `fastmap_accurate' is set to zero;
  4850.      `re_nsub' is set to the number of groups in PATTERN;
  4851.      `not_bol' and `not_eol' are set to zero.
  4852.    
  4853.    The `fastmap' and `newline_anchor' fields are neither
  4854.    examined nor set.  */
  4855.  
  4856.  
  4857.  
  4858. #ifdef __STDC__
  4859. RX_DECL reg_errcode_t
  4860. rx_compile (__const__ char *pattern, int size,
  4861.         reg_syntax_t syntax,
  4862.         struct re_pattern_buffer * rxb) 
  4863. #else
  4864. RX_DECL reg_errcode_t
  4865. rx_compile (pattern, size, syntax, rxb)
  4866.      __const__ char *pattern;
  4867.      int size;
  4868.      reg_syntax_t syntax;
  4869.      struct re_pattern_buffer * rxb;
  4870. #endif
  4871. {
  4872.   RX_subset
  4873.     inverse_translate [CHAR_SET_SIZE * rx_bitset_numb_subsets(CHAR_SET_SIZE)];
  4874.   char
  4875.     validate_inv_tr [CHAR_SET_SIZE * rx_bitset_numb_subsets(CHAR_SET_SIZE)];
  4876.  
  4877.   /* We fetch characters from PATTERN here.  Even though PATTERN is
  4878.      `char *' (i.e., signed), we declare these variables as unsigned, so
  4879.      they can be reliably used as array indices.  */
  4880.   register unsigned char c, c1;
  4881.   
  4882.   /* A random tempory spot in PATTERN.  */
  4883.   __const__ char *p1;
  4884.   
  4885.   /* Keeps track of unclosed groups.  */
  4886.   compile_stack_type compile_stack;
  4887.  
  4888.   /* Points to the current (ending) position in the pattern.  */
  4889.   __const__ char *p = pattern;
  4890.   __const__ char *pend = pattern + size;
  4891.   
  4892.   /* How to translate the characters in the pattern.  */
  4893.   unsigned char *translate = (rxb->translate
  4894.                   ? rxb->translate
  4895.                   : rx_id_translation);
  4896.  
  4897.   /* When parsing is done, this will hold the expression tree. */
  4898.   struct rexp_node * rexp = 0;
  4899.  
  4900.   /* In the midst of compilation, this holds onto the regexp 
  4901.    * first parst while rexp goes on to aquire additional constructs.
  4902.    */
  4903.   struct rexp_node * orig_rexp = 0;
  4904.   struct rexp_node * fewer_side_effects = 0;
  4905.  
  4906.   /* This and top_expression are saved on the compile stack. */
  4907.   struct rexp_node ** top_expression = &rexp;
  4908.   struct rexp_node ** last_expression = top_expression;
  4909.   
  4910.   /* Parameter to `goto append_node' */
  4911.   struct rexp_node * append;
  4912.  
  4913.   /* Counts open-groups as they are encountered.  This is the index of the
  4914.    * innermost group being compiled.
  4915.    */
  4916.   regnum_t regnum = 0;
  4917.  
  4918.   /* Place in the uncompiled pattern (i.e., the {) to
  4919.    * which to go back if the interval is invalid.  
  4920.    */
  4921.   __const__ char *beg_interval;
  4922.  
  4923.   struct re_se_params * params = 0;
  4924.   int paramc = 0;        /* How many complex side effects so far? */
  4925.  
  4926.   rx_side_effect side;        /* param to `goto add_side_effect' */
  4927.  
  4928.   bzero (validate_inv_tr, sizeof (validate_inv_tr));
  4929.  
  4930.   rxb->rx.instruction_table = rx_id_instruction_table;
  4931.  
  4932.  
  4933.   /* Initialize the compile stack.  */
  4934.   compile_stack.stack =  (( compile_stack_elt_t *) malloc ((INIT_COMPILE_STACK_SIZE) * sizeof ( compile_stack_elt_t)));
  4935.   if (compile_stack.stack == 0)
  4936.     return REG_ESPACE;
  4937.  
  4938.   compile_stack.size = INIT_COMPILE_STACK_SIZE;
  4939.   compile_stack.avail = 0;
  4940.  
  4941.   /* Initialize the pattern buffer.  */
  4942.   rxb->rx.cache = &default_cache;
  4943.   rxb->syntax = syntax;
  4944.   rxb->fastmap_accurate = 0;
  4945.   rxb->not_bol = rxb->not_eol = 0;
  4946.   rxb->least_subs = 0;
  4947.   
  4948.   /* Always count groups, whether or not rxb->no_sub is set.  
  4949.    * The whole pattern is implicitly group 0, so counting begins
  4950.    * with 1.
  4951.    */
  4952.   rxb->re_nsub = 0;
  4953.  
  4954. #if !defined (emacs) && !defined (SYNTAX_TABLE)
  4955.   /* Initialize the syntax table.  */
  4956.    init_syntax_once ();
  4957. #endif
  4958.  
  4959.   /* Loop through the uncompiled pattern until we're at the end.  */
  4960.   while (p != pend)
  4961.     {
  4962.       PATFETCH (c);
  4963.  
  4964.       switch (c)
  4965.         {
  4966.         case '^':
  4967.           {
  4968.             if (   /* If at start of pattern, it's an operator.  */
  4969.                    p == pattern + 1
  4970.                    /* If context independent, it's an operator.  */
  4971.                 || syntax & RE_CONTEXT_INDEP_ANCHORS
  4972.                    /* Otherwise, depends on what's come before.  */
  4973.                 || at_begline_loc_p (pattern, p, syntax))
  4974.           {
  4975.         struct rexp_node * n
  4976.           = rx_mk_r_side_effect (&rxb->rx, (rx_side_effect)re_se_hat);
  4977.         if (!n)
  4978.           return REG_ESPACE;
  4979.         append = n;
  4980.         goto append_node;
  4981.           }
  4982.             else
  4983.               goto normal_char;
  4984.           }
  4985.           break;
  4986.  
  4987.  
  4988.         case '$':
  4989.           {
  4990.             if (   /* If at end of pattern, it's an operator.  */
  4991.                    p == pend 
  4992.                    /* If context independent, it's an operator.  */
  4993.                 || syntax & RE_CONTEXT_INDEP_ANCHORS
  4994.                    /* Otherwise, depends on what's next.  */
  4995.                 || at_endline_loc_p (p, pend, syntax))
  4996.           {
  4997.         struct rexp_node * n
  4998.           = rx_mk_r_side_effect (&rxb->rx, (rx_side_effect)re_se_dollar);
  4999.         if (!n)
  5000.           return REG_ESPACE;
  5001.         append = n;
  5002.         goto append_node;
  5003.           }
  5004.              else
  5005.                goto normal_char;
  5006.            }
  5007.            break;
  5008.  
  5009.  
  5010.     case '+':
  5011.         case '?':
  5012.           if ((syntax & RE_BK_PLUS_QM)
  5013.               || (syntax & RE_LIMITED_OPS))
  5014.             goto normal_char;
  5015.  
  5016.         handle_plus:
  5017.         case '*':
  5018.           /* If there is no previous pattern... */
  5019.           if (pointless_if_repeated (*last_expression, params))
  5020.             {
  5021.               if (syntax & RE_CONTEXT_INVALID_OPS)
  5022.                 return REG_BADRPT;
  5023.               else if (!(syntax & RE_CONTEXT_INDEP_OPS))
  5024.                 goto normal_char;
  5025.             }
  5026.  
  5027.           {
  5028.             /* 1 means zero (many) matches is allowed.  */
  5029.             char zero_times_ok = 0, many_times_ok = 0;
  5030.  
  5031.             /* If there is a sequence of repetition chars, collapse it
  5032.                down to just one (the right one).  We can't combine
  5033.                interval operators with these because of, e.g., `a{2}*',
  5034.                which should only match an even number of `a's.  */
  5035.  
  5036.             for (;;)
  5037.               {
  5038.                 zero_times_ok |= c != '+';
  5039.                 many_times_ok |= c != '?';
  5040.  
  5041.                 if (p == pend)
  5042.                   break;
  5043.  
  5044.                 PATFETCH (c);
  5045.  
  5046.                 if (c == '*'
  5047.                     || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
  5048.                   ;
  5049.  
  5050.                 else if (syntax & RE_BK_PLUS_QM  &&  c == '\\')
  5051.                   {
  5052.                     if (p == pend) return REG_EESCAPE;
  5053.  
  5054.                     PATFETCH (c1);
  5055.                     if (!(c1 == '+' || c1 == '?'))
  5056.                       {
  5057.                         PATUNFETCH;
  5058.                         PATUNFETCH;
  5059.                         break;
  5060.                       }
  5061.  
  5062.                     c = c1;
  5063.                   }
  5064.                 else
  5065.                   {
  5066.                     PATUNFETCH;
  5067.                     break;
  5068.                   }
  5069.  
  5070.                 /* If we get here, we found another repeat character.  */
  5071.                }
  5072.  
  5073.             /* Star, etc. applied to an empty pattern is equivalent
  5074.                to an empty pattern.  */
  5075.             if (!last_expression)
  5076.               break;
  5077.  
  5078.         /* Now we know whether or not zero matches is allowed
  5079.          * and also whether or not two or more matches is allowed.
  5080.          */
  5081.  
  5082.         {
  5083.           struct rexp_node * inner_exp = *last_expression;
  5084.           int need_sync = 0;
  5085.  
  5086.           if (many_times_ok
  5087.           && has_non_idempotent_epsilon_path (&rxb->rx,
  5088.                               inner_exp, params))
  5089.         {
  5090.           struct rexp_node * pusher
  5091.             = rx_mk_r_side_effect (&rxb->rx,
  5092.                        (rx_side_effect)re_se_pushpos);
  5093.           struct rexp_node * checker
  5094.             = rx_mk_r_side_effect (&rxb->rx,
  5095.                        (rx_side_effect)re_se_chkpos);
  5096.           struct rexp_node * pushback
  5097.             = rx_mk_r_side_effect (&rxb->rx,
  5098.                        (rx_side_effect)re_se_pushback);
  5099.           rx_Bitset cs = rx_cset (&rxb->rx);
  5100.           struct rexp_node * lit_t = rx_mk_r_cset (&rxb->rx, cs);
  5101.           struct rexp_node * fake_state
  5102.             = rx_mk_r_concat (&rxb->rx, pushback, lit_t);
  5103.           struct rexp_node * phase2
  5104.             = rx_mk_r_concat (&rxb->rx, checker, fake_state);
  5105.           struct rexp_node * popper
  5106.             = rx_mk_r_side_effect (&rxb->rx,
  5107.                        (rx_side_effect)re_se_poppos);
  5108.           struct rexp_node * star
  5109.             = rx_mk_r_2phase_star (&rxb->rx, inner_exp, phase2);
  5110.           struct rexp_node * a
  5111.             = rx_mk_r_concat (&rxb->rx, pusher, star);
  5112.           struct rexp_node * whole_thing
  5113.             = rx_mk_r_concat (&rxb->rx, a, popper);
  5114.           if (!(pusher && star && pushback && lit_t && fake_state
  5115.             && lit_t && phase2 && checker && popper
  5116.             && a && whole_thing))
  5117.             return REG_ESPACE;
  5118.           RX_bitset_enjoin (cs, 't');
  5119.           *last_expression = whole_thing;
  5120.         }
  5121.           else
  5122.         {
  5123.           struct rexp_node * star =
  5124.             (many_times_ok ? rx_mk_r_star : rx_mk_r_opt)
  5125.               (&rxb->rx, *last_expression);
  5126.           if (!star)
  5127.             return REG_ESPACE;
  5128.           *last_expression = star;
  5129.           need_sync = has_any_se (&rxb->rx, *last_expression);
  5130.         }
  5131.           if (!zero_times_ok)
  5132.         {
  5133.           struct rexp_node * concat
  5134.             = rx_mk_r_concat (&rxb->rx, inner_exp,
  5135.                       rx_copy_rexp (&rxb->rx,
  5136.                             *last_expression));
  5137.           if (!concat)
  5138.             return REG_ESPACE;
  5139.           *last_expression = concat;
  5140.         }
  5141.           if (need_sync)
  5142.         {
  5143.           int sync_se = paramc;
  5144.           params = (params
  5145.                 ? ((struct re_se_params *)
  5146.                    realloc (params,
  5147.                     sizeof (*params) * (1 + paramc)))
  5148.                 : ((struct re_se_params *)
  5149.                    malloc (sizeof (*params))));
  5150.           if (!params)
  5151.             return REG_ESPACE;
  5152.           ++paramc;
  5153.           params [sync_se].se = re_se_tv;
  5154.           side = (rx_side_effect)sync_se;
  5155.           goto add_side_effect;
  5156.         }
  5157.         }
  5158.         /* The old regex.c used to optimize `.*\n'.  
  5159.          * Maybe rx should too?
  5160.          */
  5161.       }
  5162.       break;
  5163.  
  5164.  
  5165.     case '.':
  5166.       {
  5167.         rx_Bitset cs = rx_cset (&rxb->rx);
  5168.         struct rexp_node * n = rx_mk_r_cset (&rxb->rx, cs);
  5169.         if (!(cs && n))
  5170.           return REG_ESPACE;
  5171.  
  5172.         rx_bitset_universe (rxb->rx.local_cset_size, cs);
  5173.         if (!(rxb->syntax & RE_DOT_NEWLINE))
  5174.           RX_bitset_remove (cs, '\n');
  5175.         if (!(rxb->syntax & RE_DOT_NOT_NULL))
  5176.           RX_bitset_remove (cs, 0);
  5177.  
  5178.         append = n;
  5179.         goto append_node;
  5180.         break;
  5181.       }
  5182.  
  5183.  
  5184.         case '[':
  5185.       if (p == pend) return REG_EBRACK;
  5186.           {
  5187.             boolean had_char_class = false;
  5188.         rx_Bitset cs = rx_cset (&rxb->rx);
  5189.         struct rexp_node * node = rx_mk_r_cset (&rxb->rx, cs);
  5190.         int is_inverted = *p == '^';
  5191.         
  5192.         if (!(node && cs))
  5193.           return REG_ESPACE;
  5194.         
  5195.         /* This branch of the switch is normally exited with
  5196.          *`goto append_node'
  5197.          */
  5198.         append = node;
  5199.         
  5200.             if (is_inverted)
  5201.           p++;
  5202.         
  5203.             /* Remember the first position in the bracket expression.  */
  5204.             p1 = p;
  5205.         
  5206.             /* Read in characters and ranges, setting map bits.  */
  5207.             for (;;)
  5208.               {
  5209.                 if (p == pend) return REG_EBRACK;
  5210.         
  5211.                 PATFETCH (c);
  5212.         
  5213.                 /* \ might escape characters inside [...] and [^...].  */
  5214.                 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
  5215.                   {
  5216.                     if (p == pend) return REG_EESCAPE;
  5217.             
  5218.                     PATFETCH (c1);
  5219.             {
  5220.               rx_Bitset it = inverse_translation (rxb, 
  5221.                               validate_inv_tr,
  5222.                               inverse_translate,
  5223.                               translate,
  5224.                               c1);
  5225.               rx_bitset_union (rxb->rx.local_cset_size, cs, it);
  5226.             }
  5227.                     continue;
  5228.                   }
  5229.         
  5230.                 /* Could be the end of the bracket expression.  If it's
  5231.                    not (i.e., when the bracket expression is `[]' so
  5232.                    far), the ']' character bit gets set way below.  */
  5233.                 if (c == ']' && p != p1 + 1)
  5234.                   goto finalize_class_and_append;
  5235.         
  5236.                 /* Look ahead to see if it's a range when the last thing
  5237.                    was a character class.  */
  5238.                 if (had_char_class && c == '-' && *p != ']')
  5239.                   return REG_ERANGE;
  5240.         
  5241.                 /* Look ahead to see if it's a range when the last thing
  5242.                    was a character: if this is a hyphen not at the
  5243.                    beginning or the end of a list, then it's the range
  5244.                    operator.  */
  5245.                 if (c == '-' 
  5246.                     && !(p - 2 >= pattern && p[-2] == '[') 
  5247.                     && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
  5248.                     && *p != ']')
  5249.                   {
  5250.                     reg_errcode_t ret
  5251.                       = compile_range (rxb, cs, &p, pend, translate, syntax,
  5252.                        inverse_translate, validate_inv_tr);
  5253.                     if (ret != REG_NOERROR) return ret;
  5254.                   }
  5255.         
  5256.                 else if (p[0] == '-' && p[1] != ']')
  5257.                   { /* This handles ranges made up of characters only.  */
  5258.                     reg_errcode_t ret;
  5259.             
  5260.             /* Move past the `-'.  */
  5261.                     PATFETCH (c1);
  5262.                     
  5263.                     ret = compile_range (rxb, cs, &p, pend, translate, syntax,
  5264.                      inverse_translate, validate_inv_tr);
  5265.                     if (ret != REG_NOERROR) return ret;
  5266.                   }
  5267.         
  5268.                 /* See if we're at the beginning of a possible character
  5269.                    class.  */
  5270.         
  5271.         else if ((syntax & RE_CHAR_CLASSES)
  5272.              && (c == '[') && (*p == ':'))
  5273.                   {
  5274.                     char str[CHAR_CLASS_MAX_LENGTH + 1];
  5275.             
  5276.                     PATFETCH (c);
  5277.                     c1 = 0;
  5278.             
  5279.                     /* If pattern is `[[:'.  */
  5280.                     if (p == pend) return REG_EBRACK;
  5281.             
  5282.                     for (;;)
  5283.                       {
  5284.                         PATFETCH (c);
  5285.                         if (c == ':' || c == ']' || p == pend
  5286.                             || c1 == CHAR_CLASS_MAX_LENGTH)
  5287.               break;
  5288.                         str[c1++] = c;
  5289.                       }
  5290.                     str[c1] = '\0';
  5291.             
  5292.                     /* If isn't a word bracketed by `[:' and:`]':
  5293.                        undo the ending character, the letters, and leave 
  5294.                        the leading `:' and `[' (but set bits for them).  */
  5295.                     if (c == ':' && *p == ']')
  5296.                       {
  5297.                         int ch;
  5298.                         boolean is_alnum = !strcmp (str, "alnum");
  5299.                         boolean is_alpha = !strcmp (str, "alpha");
  5300.                         boolean is_blank = !strcmp (str, "blank");
  5301.                         boolean is_cntrl = !strcmp (str, "cntrl");
  5302.                         boolean is_digit = !strcmp (str, "digit");
  5303.                         boolean is_graph = !strcmp (str, "graph");
  5304.                         boolean is_lower = !strcmp (str, "lower");
  5305.                         boolean is_print = !strcmp (str, "print");
  5306.                         boolean is_punct = !strcmp (str, "punct");
  5307.                         boolean is_space = !strcmp (str, "space");
  5308.                         boolean is_upper = !strcmp (str, "upper");
  5309.                         boolean is_xdigit = !strcmp (str, "xdigit");
  5310.                         
  5311.                         if (!IS_CHAR_CLASS (str)) return REG_ECTYPE;
  5312.             
  5313.                         /* Throw away the ] at the end of the character
  5314.                            class.  */
  5315.                         PATFETCH (c);                    
  5316.             
  5317.                         if (p == pend) return REG_EBRACK;
  5318.             
  5319.                         for (ch = 0; ch < 1 << CHARBITS; ch++)
  5320.                           {
  5321.                             if (   (is_alnum  && isalnum (ch))
  5322.                                 || (is_alpha  && isalpha (ch))
  5323.                                 || (is_blank  && isblank (ch))
  5324.                                 || (is_cntrl  && iscntrl (ch))
  5325.                                 || (is_digit  && isdigit (ch))
  5326.                                 || (is_graph  && isgraph (ch))
  5327.                                 || (is_lower  && islower (ch))
  5328.                                 || (is_print  && isprint (ch))
  5329.                                 || (is_punct  && ispunct (ch))
  5330.                                 || (is_space  && isspace (ch))
  5331.                                 || (is_upper  && isupper (ch))
  5332.                                 || (is_xdigit && isxdigit (ch)))
  5333.                   {
  5334.                 rx_Bitset it =
  5335.                   inverse_translation (rxb, 
  5336.                                validate_inv_tr,
  5337.                                inverse_translate,
  5338.                                translate,
  5339.                                ch);
  5340.                 rx_bitset_union (rxb->rx.local_cset_size,
  5341.                          cs, it);
  5342.                   }
  5343.                           }
  5344.                         had_char_class = true;
  5345.                       }
  5346.                     else
  5347.                       {
  5348.                         c1++;
  5349.                         while (c1--)    
  5350.                           PATUNFETCH;
  5351.             {
  5352.               rx_Bitset it =
  5353.                 inverse_translation (rxb, 
  5354.                          validate_inv_tr,
  5355.                          inverse_translate,
  5356.                          translate,
  5357.                          '[');
  5358.               rx_bitset_union (rxb->rx.local_cset_size,
  5359.                        cs, it);
  5360.             }
  5361.             {
  5362.               rx_Bitset it =
  5363.                 inverse_translation (rxb, 
  5364.                          validate_inv_tr,
  5365.                          inverse_translate,
  5366.                          translate,
  5367.                          ':');
  5368.               rx_bitset_union (rxb->rx.local_cset_size,
  5369.                        cs, it);
  5370.             }
  5371.                         had_char_class = false;
  5372.                       }
  5373.                   }
  5374.                 else
  5375.                   {
  5376.                     had_char_class = false;
  5377.             {
  5378.               rx_Bitset it = inverse_translation (rxb, 
  5379.                               validate_inv_tr,
  5380.                               inverse_translate,
  5381.                               translate,
  5382.                               c);
  5383.               rx_bitset_union (rxb->rx.local_cset_size, cs, it);
  5384.             }
  5385.                   }
  5386.               }
  5387.  
  5388.       finalize_class_and_append:
  5389.         if (is_inverted)
  5390.           {
  5391.         rx_bitset_complement (rxb->rx.local_cset_size, cs);
  5392.         if (syntax & RE_HAT_LISTS_NOT_NEWLINE)
  5393.           RX_bitset_remove (cs, '\n');
  5394.           }
  5395.         goto append_node;
  5396.           }
  5397.           break;
  5398.  
  5399.  
  5400.     case '(':
  5401.           if (syntax & RE_NO_BK_PARENS)
  5402.             goto handle_open;
  5403.           else
  5404.             goto normal_char;
  5405.  
  5406.  
  5407.         case ')':
  5408.           if (syntax & RE_NO_BK_PARENS)
  5409.             goto handle_close;
  5410.           else
  5411.             goto normal_char;
  5412.  
  5413.  
  5414.         case '\n':
  5415.           if (syntax & RE_NEWLINE_ALT)
  5416.             goto handle_alt;
  5417.           else
  5418.             goto normal_char;
  5419.  
  5420.  
  5421.     case '|':
  5422.           if (syntax & RE_NO_BK_VBAR)
  5423.             goto handle_alt;
  5424.           else
  5425.             goto normal_char;
  5426.  
  5427.  
  5428.         case '{':
  5429.       if ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
  5430.         goto handle_interval;
  5431.       else
  5432.         goto normal_char;
  5433.  
  5434.  
  5435.         case '\\':
  5436.           if (p == pend) return REG_EESCAPE;
  5437.  
  5438.           /* Do not translate the character after the \, so that we can
  5439.              distinguish, e.g., \B from \b, even if we normally would
  5440.              translate, e.g., B to b.  */
  5441.           PATFETCH_RAW (c);
  5442.  
  5443.           switch (c)
  5444.             {
  5445.             case '(':
  5446.               if (syntax & RE_NO_BK_PARENS)
  5447.                 goto normal_backslash;
  5448.  
  5449.             handle_open:
  5450.               rxb->re_nsub++;
  5451.               regnum++;
  5452.               if (COMPILE_STACK_FULL)
  5453.                 { 
  5454.                   ((compile_stack.stack) =
  5455.            (compile_stack_elt_t *) realloc (compile_stack.stack, ( compile_stack.size << 1) * sizeof (
  5456.                                                           compile_stack_elt_t)));
  5457.                   if (compile_stack.stack == 0) return REG_ESPACE;
  5458.  
  5459.                   compile_stack.size <<= 1;
  5460.                 }
  5461.  
  5462.           if (*last_expression)
  5463.         {
  5464.           struct rexp_node * concat
  5465.             = rx_mk_r_concat (&rxb->rx, *last_expression, 0);
  5466.           if (!concat)
  5467.             return REG_ESPACE;
  5468.           *last_expression = concat;
  5469.           last_expression = &concat->params.pair.right;
  5470.         }
  5471.  
  5472.               /*
  5473.            * These are the values to restore when we hit end of this
  5474.                * group.  
  5475.            */
  5476.           COMPILE_STACK_TOP.top_expression = top_expression;
  5477.           COMPILE_STACK_TOP.last_expression = last_expression;
  5478.               COMPILE_STACK_TOP.regnum = regnum;
  5479.           
  5480.               compile_stack.avail++;
  5481.           
  5482.           top_expression = last_expression;
  5483.           break;
  5484.  
  5485.  
  5486.             case ')':
  5487.               if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
  5488.  
  5489.             handle_close:
  5490.               /* See similar code for backslashed left paren above.  */
  5491.               if (COMPILE_STACK_EMPTY)
  5492.                 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
  5493.                   goto normal_char;
  5494.                 else
  5495.                   return REG_ERPAREN;
  5496.  
  5497.               /* Since we just checked for an empty stack above, this
  5498.                  ``can't happen''.  */
  5499.  
  5500.               {
  5501.                 /* We don't just want to restore into `regnum', because
  5502.                    later groups should continue to be numbered higher,
  5503.                    as in `(ab)c(de)' -- the second group is #2.  */
  5504.                 regnum_t this_group_regnum;
  5505.         struct rexp_node ** inner = top_expression;
  5506.  
  5507.                 compile_stack.avail--;
  5508.         top_expression = COMPILE_STACK_TOP.top_expression;
  5509.         last_expression = COMPILE_STACK_TOP.last_expression;
  5510.                 this_group_regnum = COMPILE_STACK_TOP.regnum;
  5511.         {
  5512.           int left_se = paramc;
  5513.           int right_se = paramc + 1;
  5514.  
  5515.           params = (params
  5516.                 ? ((struct re_se_params *)
  5517.                    realloc (params,
  5518.                     (paramc + 2) * sizeof (params[0])))
  5519.                 : ((struct re_se_params *)
  5520.                    malloc (2 * sizeof (params[0]))));
  5521.           if (!params)
  5522.             return REG_ESPACE;
  5523.           paramc += 2;
  5524.  
  5525.           params[left_se].se = re_se_lparen;
  5526.           params[left_se].op1 = this_group_regnum;
  5527.           params[right_se].se = re_se_rparen;
  5528.           params[right_se].op1 = this_group_regnum;
  5529.           {
  5530.             struct rexp_node * left
  5531.               = rx_mk_r_side_effect (&rxb->rx,
  5532.                          (rx_side_effect)left_se);
  5533.             struct rexp_node * right
  5534.               = rx_mk_r_side_effect (&rxb->rx,
  5535.                          (rx_side_effect)right_se);
  5536.             struct rexp_node * c1
  5537.               = (*inner
  5538.              ? rx_mk_r_concat (&rxb->rx, left, *inner) : left);
  5539.             struct rexp_node * c2
  5540.               = rx_mk_r_concat (&rxb->rx, c1, right);
  5541.             if (!(left && right && c1 && c2))
  5542.               return REG_ESPACE;
  5543.             *inner = c2;
  5544.           }
  5545.         }
  5546.         break;
  5547.           }
  5548.  
  5549.             case '|':                    /* `\|'.  */
  5550.               if ((syntax & RE_LIMITED_OPS) || (syntax & RE_NO_BK_VBAR))
  5551.                 goto normal_backslash;
  5552.             handle_alt:
  5553.               if (syntax & RE_LIMITED_OPS)
  5554.                 goto normal_char;
  5555.  
  5556.           {
  5557.         struct rexp_node * alt
  5558.           = rx_mk_r_alternate (&rxb->rx, *top_expression, 0);
  5559.         if (!alt)
  5560.           return REG_ESPACE;
  5561.         *top_expression = alt;
  5562.         last_expression = &alt->params.pair.right;
  5563.         {
  5564.           int sync_se = paramc;
  5565.  
  5566.           params = (params
  5567.                 ? ((struct re_se_params *)
  5568.                    realloc (params,
  5569.                     (paramc + 1) * sizeof (params[0])))
  5570.                 : ((struct re_se_params *)
  5571.                    malloc (sizeof (params[0]))));
  5572.           if (!params)
  5573.             return REG_ESPACE;
  5574.           ++paramc;
  5575.  
  5576.           params[sync_se].se = re_se_tv;
  5577.           {
  5578.             struct rexp_node * sync
  5579.               = rx_mk_r_side_effect (&rxb->rx,
  5580.                          (rx_side_effect)sync_se);
  5581.             struct rexp_node * conc
  5582.               = rx_mk_r_concat (&rxb->rx, sync, 0);
  5583.  
  5584.             if (!sync || !conc)
  5585.               return REG_ESPACE;
  5586.  
  5587.             *last_expression = conc;
  5588.             last_expression = &conc->params.pair.right;
  5589.           }
  5590.         }
  5591.           }
  5592.               break;
  5593.  
  5594.  
  5595.             case '{': 
  5596.               /* If \{ is a literal.  */
  5597.               if (!(syntax & RE_INTERVALS)
  5598.                      /* If we're at `\{' and it's not the open-interval 
  5599.                         operator.  */
  5600.                   || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
  5601.                   || (p - 2 == pattern  &&  p == pend))
  5602.                 goto normal_backslash;
  5603.  
  5604.             handle_interval:
  5605.               {
  5606.                 /* If got here, then the syntax allows intervals.  */
  5607.  
  5608.                 /* At least (most) this many matches must be made.  */
  5609.                 int lower_bound = -1, upper_bound = -1;
  5610.  
  5611.                 beg_interval = p - 1;
  5612.  
  5613.                 if (p == pend)
  5614.                   {
  5615.                     if (syntax & RE_NO_BK_BRACES)
  5616.                       goto unfetch_interval;
  5617.                     else
  5618.                       return REG_EBRACE;
  5619.                   }
  5620.  
  5621.                 GET_UNSIGNED_NUMBER (lower_bound);
  5622.  
  5623.                 if (c == ',')
  5624.                   {
  5625.                     GET_UNSIGNED_NUMBER (upper_bound);
  5626.                     if (upper_bound < 0) upper_bound = RE_DUP_MAX;
  5627.                   }
  5628.                 else
  5629.                   /* Interval such as `{1}' => match exactly once. */
  5630.                   upper_bound = lower_bound;
  5631.  
  5632.                 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
  5633.                     || lower_bound > upper_bound)
  5634.                   {
  5635.                     if (syntax & RE_NO_BK_BRACES)
  5636.                       goto unfetch_interval;
  5637.                     else 
  5638.                       return REG_BADBR;
  5639.                   }
  5640.  
  5641.                 if (!(syntax & RE_NO_BK_BRACES)) 
  5642.                   {
  5643.                     if (c != '\\') return REG_EBRACE;
  5644.                     PATFETCH (c);
  5645.                   }
  5646.  
  5647.                 if (c != '}')
  5648.                   {
  5649.                     if (syntax & RE_NO_BK_BRACES)
  5650.                       goto unfetch_interval;
  5651.                     else 
  5652.                       return REG_BADBR;
  5653.                   }
  5654.  
  5655.                 /* We just parsed a valid interval.  */
  5656.  
  5657.                 /* If it's invalid to have no preceding re.  */
  5658.                 if (pointless_if_repeated (*last_expression, params))
  5659.                   {
  5660.                     if (syntax & RE_CONTEXT_INVALID_OPS)
  5661.                       return REG_BADRPT;
  5662.                     else if (!(syntax & RE_CONTEXT_INDEP_OPS))
  5663.                       goto unfetch_interval;
  5664.             /* was: else laststart = b; */
  5665.                   }
  5666.  
  5667.                 /* If the upper bound is zero, don't want to iterate
  5668.                  * at all.
  5669.          */
  5670.                  if (upper_bound == 0)
  5671.            {
  5672.              if (*last_expression)
  5673.                {
  5674.              rx_free_rexp (&rxb->rx, *last_expression);
  5675.              *last_expression = 0;
  5676.                }
  5677.            }
  5678.         else
  5679.           /* Otherwise, we have a nontrivial interval. */
  5680.           {
  5681.             int iter_se = paramc;
  5682.             int end_se = paramc + 1;
  5683.             params = (params
  5684.                   ? ((struct re_se_params *)
  5685.                  realloc (params,
  5686.                       sizeof (*params) * (2 + paramc)))
  5687.                   : ((struct re_se_params *)
  5688.                  malloc (2 * sizeof (*params))));
  5689.             if (!params)
  5690.               return REG_ESPACE;
  5691.             paramc += 2;
  5692.             params [iter_se].se = re_se_iter;
  5693.             params [iter_se].op1 = lower_bound;
  5694.             params[iter_se].op2 = upper_bound;
  5695.  
  5696.             params[end_se].se = re_se_end_iter;
  5697.             params[end_se].op1 = lower_bound;
  5698.             params[end_se].op2 = upper_bound;
  5699.             {
  5700.               struct rexp_node * push0
  5701.             = rx_mk_r_side_effect (&rxb->rx,
  5702.                            (rx_side_effect)re_se_push0);
  5703.               struct rexp_node * start_one_iter
  5704.             = rx_mk_r_side_effect (&rxb->rx,
  5705.                            (rx_side_effect)iter_se);
  5706.               struct rexp_node * phase1
  5707.             = rx_mk_r_concat (&rxb->rx, start_one_iter,
  5708.                       *last_expression);
  5709.               struct rexp_node * pushback
  5710.             = rx_mk_r_side_effect (&rxb->rx,
  5711.                            (rx_side_effect)re_se_pushback);
  5712.               rx_Bitset cs = rx_cset (&rxb->rx);
  5713.               struct rexp_node * lit_t
  5714.             = rx_mk_r_cset (&rxb->rx, cs);
  5715.               struct rexp_node * phase2
  5716.             = rx_mk_r_concat (&rxb->rx, pushback, lit_t);
  5717.               struct rexp_node * loop
  5718.             = rx_mk_r_2phase_star (&rxb->rx, phase1, phase2);
  5719.               struct rexp_node * push_n_loop
  5720.             = rx_mk_r_concat (&rxb->rx, push0, loop);
  5721.               struct rexp_node * final_test
  5722.             = rx_mk_r_side_effect (&rxb->rx,
  5723.                            (rx_side_effect)end_se);
  5724.               struct rexp_node * full_exp
  5725.             = rx_mk_r_concat (&rxb->rx, push_n_loop, final_test);
  5726.  
  5727.               if (!(push0 && start_one_iter && phase1
  5728.                 && pushback && lit_t && phase2
  5729.                 && loop && push_n_loop && final_test && full_exp))
  5730.             return REG_ESPACE;
  5731.  
  5732.               RX_bitset_enjoin(cs, 't');
  5733.  
  5734.               *last_expression = full_exp;
  5735.             }
  5736.           }
  5737.                 beg_interval = 0;
  5738.               }
  5739.               break;
  5740.  
  5741.             unfetch_interval:
  5742.               /* If an invalid interval, match the characters as literals.  */
  5743.                p = beg_interval;
  5744.                beg_interval = NULL;
  5745.  
  5746.                /* normal_char and normal_backslash need `c'.  */
  5747.                PATFETCH (c);    
  5748.  
  5749.                if (!(syntax & RE_NO_BK_BRACES))
  5750.                  {
  5751.                    if (p > pattern  &&  p[-1] == '\\')
  5752.                      goto normal_backslash;
  5753.                  }
  5754.                goto normal_char;
  5755.  
  5756. #ifdef emacs
  5757.             /* There is no way to specify the before_dot and after_dot
  5758.                operators.  rms says this is ok.  --karl  */
  5759.             case '=':
  5760.           side = at_dot;
  5761.           goto add_side_effect;
  5762.               break;
  5763.  
  5764.             case 's':
  5765.         case 'S':
  5766.           {
  5767.         rx_Bitset cs = cset (&rxb->rx);
  5768.         struct rexp_node * set = rx_mk_r_cset (&rxb->rx, cs);
  5769.         if (!(cs && set))
  5770.           return REG_ESPACE;
  5771.         if (c == 'S')
  5772.           rx_bitset_universe (rxb->rx.local_cset_size, cs);
  5773.  
  5774.         PATFETCH (c);
  5775.         {
  5776.           int x;
  5777.           char code = syntax_spec_code (c);
  5778.           for (x = 0; x < 256; ++x)
  5779.             {
  5780.               
  5781.               if (SYNTAX (x) & code)
  5782.             {
  5783.               rx_Bitset it =
  5784.                 inverse_translation (rxb, validate_inv_tr,
  5785.                          inverse_translate,
  5786.                          translate, x);
  5787.               rx_bitset_xor (rxb->rx.local_cset_size, cs, it);
  5788.             }
  5789.             }
  5790.         }
  5791.         goto append_node;
  5792.           }
  5793.               break;
  5794. #endif /* emacs */
  5795.  
  5796.  
  5797.             case 'w':
  5798.             case 'W':
  5799.           {
  5800.         rx_Bitset cs = rx_cset (&rxb->rx);
  5801.         struct rexp_node * n = (cs ? rx_mk_r_cset (&rxb->rx, cs) : 0);
  5802.         if (!(cs && n))
  5803.           return REG_ESPACE;
  5804.         if (c == 'W')
  5805.           rx_bitset_universe (rxb->rx.local_cset_size ,cs);
  5806.         {
  5807.           int x;
  5808.           for (x = rxb->rx.local_cset_size - 1; x > 0; --x)
  5809.             if (re_syntax_table[x] & Sword)
  5810.               RX_bitset_toggle (cs, x);
  5811.         }
  5812.         append = n;
  5813.         goto append_node;
  5814.           }
  5815.               break;
  5816.  
  5817. /* With a little extra work, some of these side effects could be optimized
  5818.  * away (basicly by looking at what we already know about the surrounding
  5819.  * chars).  
  5820.  */
  5821.             case '<':
  5822.           side = (rx_side_effect)re_se_wordbeg;
  5823.           goto add_side_effect;
  5824.               break;
  5825.  
  5826.             case '>':
  5827.               side = (rx_side_effect)re_se_wordend;
  5828.           goto add_side_effect;
  5829.               break;
  5830.  
  5831.             case 'b':
  5832.               side = (rx_side_effect)re_se_wordbound;
  5833.           goto add_side_effect;
  5834.               break;
  5835.  
  5836.             case 'B':
  5837.               side = (rx_side_effect)re_se_notwordbound;
  5838.           goto add_side_effect;
  5839.               break;
  5840.  
  5841.             case '`':
  5842.           side = (rx_side_effect)re_se_begbuf;
  5843.           goto add_side_effect;
  5844.           break;
  5845.           
  5846.             case '\'':
  5847.           side = (rx_side_effect)re_se_endbuf;
  5848.           goto add_side_effect;
  5849.               break;
  5850.  
  5851.         add_side_effect:
  5852.           {
  5853.         struct rexp_node * se
  5854.           = rx_mk_r_side_effect (&rxb->rx, side);
  5855.         if (!se)
  5856.           return REG_ESPACE;
  5857.         append = se;
  5858.         goto append_node;
  5859.           }
  5860.           break;
  5861.  
  5862.             case '1': case '2': case '3': case '4': case '5':
  5863.             case '6': case '7': case '8': case '9':
  5864.               if (syntax & RE_NO_BK_REFS)
  5865.                 goto normal_char;
  5866.  
  5867.               c1 = c - '0';
  5868.  
  5869.               if (c1 > regnum)
  5870.                 return REG_ESUBREG;
  5871.  
  5872.               /* Can't back reference to a subexpression if inside of it.  */
  5873.               if (group_in_compile_stack (compile_stack, c1))
  5874.         return REG_ESUBREG;
  5875.  
  5876.           {
  5877.         int backref_se = paramc;
  5878.         params = (params
  5879.               ? ((struct re_se_params *)
  5880.                  realloc (params,
  5881.                       sizeof (*params) * (1 + paramc)))
  5882.               : ((struct re_se_params *)
  5883.                  malloc (sizeof (*params))));
  5884.         if (!params)
  5885.           return REG_ESPACE;
  5886.         ++paramc;
  5887.         params[backref_se].se = re_se_backref;
  5888.         params[backref_se].op1 = c1;
  5889.         side = (rx_side_effect)backref_se;
  5890.         goto add_side_effect;
  5891.           }
  5892.               break;
  5893.  
  5894.             case '+':
  5895.             case '?':
  5896.               if (syntax & RE_BK_PLUS_QM)
  5897.                 goto handle_plus;
  5898.               else
  5899.                 goto normal_backslash;
  5900.  
  5901.             default:
  5902.             normal_backslash:
  5903.               /* You might think it would be useful for \ to mean
  5904.                  not to translate; but if we don't translate it
  5905.                  it will never match anything.  */
  5906.               c = TRANSLATE (c);
  5907.               goto normal_char;
  5908.             }
  5909.           break;
  5910.  
  5911.  
  5912.     default:
  5913.         /* Expects the character in `c'.  */
  5914.     normal_char:
  5915.         {
  5916.           rx_Bitset cs = rx_cset(&rxb->rx);
  5917.           struct rexp_node * match = rx_mk_r_cset (&rxb->rx, cs);
  5918.           rx_Bitset it;
  5919.           if (!(cs && match))
  5920.         return REG_ESPACE;
  5921.           it = inverse_translation (rxb, validate_inv_tr,
  5922.                     inverse_translate, translate, c);
  5923.           rx_bitset_union (CHAR_SET_SIZE, cs, it);
  5924.           append = match;
  5925.  
  5926.         append_node:
  5927.           /* This genericly appends the rexp APPEND to *LAST_EXPRESSION
  5928.            * and then parses the next character normally.
  5929.            */
  5930.           if (*last_expression)
  5931.         {
  5932.           struct rexp_node * concat
  5933.             = rx_mk_r_concat (&rxb->rx, *last_expression, append);
  5934.           if (!concat)
  5935.             return REG_ESPACE;
  5936.           *last_expression = concat;
  5937.           last_expression = &concat->params.pair.right;
  5938.         }
  5939.           else
  5940.         *last_expression = append;
  5941.         }
  5942.     } /* switch (c) */
  5943.     } /* while p != pend */
  5944.  
  5945.   
  5946.   {
  5947.     int win_se = paramc;
  5948.     params = (params
  5949.           ? ((struct re_se_params *)
  5950.          realloc (params,
  5951.               sizeof (*params) * (1 + paramc)))
  5952.           : ((struct re_se_params *)
  5953.          malloc (sizeof (*params))));
  5954.     if (!params)
  5955.       return REG_ESPACE;
  5956.     ++paramc;
  5957.     params[win_se].se = re_se_win;
  5958.     {
  5959.       struct rexp_node * se
  5960.     = rx_mk_r_side_effect (&rxb->rx, (rx_side_effect)win_se);
  5961.       struct rexp_node * concat
  5962.     = rx_mk_r_concat (&rxb->rx, rexp, se);
  5963.       if (!(se && concat))
  5964.     return REG_ESPACE;
  5965.       rexp = concat;
  5966.     }
  5967.   }
  5968.  
  5969.  
  5970.   /* Through the pattern now.  */
  5971.  
  5972.   if (!COMPILE_STACK_EMPTY) 
  5973.     return REG_EPAREN;
  5974.  
  5975.       free (compile_stack.stack);
  5976.  
  5977.   orig_rexp = rexp;
  5978. #ifdef RX_DEBUG
  5979.   if (rx_debug_compile)
  5980.     {
  5981.       dbug_rxb = rxb;
  5982.       fputs ("\n\nCompiling ", stdout);
  5983.       fwrite (pattern, 1, size, stdout);
  5984.       fputs (":\n", stdout);
  5985.       rxb->se_params = params;
  5986.       print_rexp (&rxb->rx, orig_rexp, 2, re_seprint, stdout);
  5987.     }
  5988. #endif
  5989.   {
  5990.     rx_Bitset cs = rx_cset(&rxb->rx);
  5991.     rx_Bitset cs2 = rx_cset(&rxb->rx);
  5992.     char * se_map = (char *) alloca (paramc);
  5993.     struct rexp_node * new_rexp = 0;
  5994.  
  5995.  
  5996.     bzero (se_map, paramc);
  5997.     find_backrefs (se_map, rexp, params);
  5998.     fewer_side_effects =
  5999.       remove_unecessary_side_effects (&rxb->rx, se_map,
  6000.                       rx_copy_rexp (&rxb->rx, rexp), params);
  6001.  
  6002.     speed_up_alt (&rxb->rx, rexp, 0);
  6003.     speed_up_alt (&rxb->rx, fewer_side_effects, 1);
  6004.  
  6005.     {
  6006.       char * syntax_parens = rxb->syntax_parens;
  6007.       if (syntax_parens == (char *)0x1)
  6008.     rexp = remove_unecessary_side_effects
  6009.       (&rxb->rx, se_map, rexp, params);
  6010.       else if (syntax_parens)
  6011.     {
  6012.       int x;
  6013.       for (x = 0; x < paramc; ++x)
  6014.         if ((   (params[x].se == re_se_lparen)
  6015.          || (params[x].se == re_se_rparen))
  6016.         && (!syntax_parens [params[x].op1]))
  6017.           se_map [x] = 1;
  6018.       rexp = remove_unecessary_side_effects
  6019.         (&rxb->rx, se_map, rexp, params);
  6020.     }
  6021.     }
  6022.  
  6023.     /* At least one more optimization would be nice to have here but i ran out 
  6024.      * of time.  The idea would be to delay side effects.  
  6025.      * For examle, `(abc)' is the same thing as `abc()' except that the
  6026.      * left paren is offset by 3 (which we know at compile time).
  6027.      * (In this comment, write that second pattern `abc(:3:)' 
  6028.      * where `(:3:' is a syntactic unit.)
  6029.      *
  6030.      * Trickier:  `(abc|defg)'  is the same as `(abc(:3:|defg(:4:))'
  6031.      * (The paren nesting may be hard to follow -- that's an alternation
  6032.      *    of `abc(:3:' and `defg(:4:' inside (purely syntactic) parens
  6033.      *  followed by the closing paren from the original expression.)
  6034.      *
  6035.      * Neither the expression tree representation nor the the nfa make
  6036.      * this very easy to write. :(
  6037.      */
  6038.  
  6039.   /* What we compile is different than what the parser returns.
  6040.    * Suppose the parser returns expression R.
  6041.    * Let R' be R with unnecessary register assignments removed 
  6042.    * (see REMOVE_UNECESSARY_SIDE_EFFECTS, above).
  6043.    *
  6044.    * What we will compile is the expression:
  6045.    *
  6046.    *    m{try}R{win}\|s{try}R'{win}
  6047.    *
  6048.    * {try} and {win} denote side effect epsilons (see EXPLORE_FUTURE).
  6049.    * 
  6050.    * When trying a match, we insert an `m' at the beginning of the 
  6051.    * string if the user wants registers to be filled, `s' if not.
  6052.    */
  6053.     new_rexp =
  6054.       rx_mk_r_alternate
  6055.     (&rxb->rx,
  6056.      rx_mk_r_concat (&rxb->rx, rx_mk_r_cset (&rxb->rx, cs2), rexp),
  6057.      rx_mk_r_concat (&rxb->rx,
  6058.              rx_mk_r_cset (&rxb->rx, cs), fewer_side_effects));
  6059.  
  6060.     if (!(new_rexp && cs && cs2))
  6061.       return REG_ESPACE;
  6062.     RX_bitset_enjoin (cs2, '\0'); /* prefixed to the rexp used for matching. */
  6063.     RX_bitset_enjoin (cs, '\1'); /* prefixed to the rexp used for searching. */
  6064.     rexp = new_rexp;
  6065.   }
  6066.  
  6067. #ifdef RX_DEBUG
  6068.   if (rx_debug_compile)
  6069.     {
  6070.       fputs ("\n...which is compiled as:\n", stdout);
  6071.       print_rexp (&rxb->rx, rexp, 2, re_seprint, stdout);
  6072.     }
  6073. #endif
  6074.   {
  6075.     struct rx_nfa_state *start = 0;
  6076.     struct rx_nfa_state *end = 0;
  6077.  
  6078.     if (!rx_build_nfa (&rxb->rx, rexp, &start, &end))
  6079.       return REG_ESPACE;    /*  */
  6080.     else
  6081.       {
  6082.     void * mem = (void *)rxb->buffer;
  6083.     unsigned long size = rxb->allocated;
  6084.     int start_id;
  6085.     char * perm_mem;
  6086.     int iterator_size = paramc * sizeof (params[0]);
  6087.  
  6088.     end->is_final = 1;
  6089.     start->is_start = 1;
  6090.     rx_name_nfa_states (&rxb->rx);
  6091.     start_id = start->id;
  6092. #ifdef RX_DEBUG
  6093.     if (rx_debug_compile)
  6094.       {
  6095.         fputs ("...giving the NFA: \n", stdout);
  6096.         dbug_rxb = rxb;
  6097.         print_nfa (&rxb->rx, rxb->rx.nfa_states, re_seprint, stdout);
  6098.       }
  6099. #endif
  6100.     if (!rx_eclose_nfa (&rxb->rx))
  6101.       return REG_ESPACE;
  6102.     else
  6103.       {
  6104.         rx_delete_epsilon_transitions (&rxb->rx);
  6105.         
  6106.         /* For compatability reasons, we need to shove the
  6107.          * compiled nfa into one chunk of malloced memory.
  6108.          */
  6109.         rxb->rx.reserved = (   sizeof (params[0]) * paramc
  6110.                 +  rx_sizeof_bitset (rxb->rx.local_cset_size));
  6111. #ifdef RX_DEBUG
  6112.         if (rx_debug_compile)
  6113.           {
  6114.         dbug_rxb = rxb;
  6115.         fputs ("...which cooks down (uncompactified) to: \n", stdout);
  6116.         print_nfa (&rxb->rx, rxb->rx.nfa_states, re_seprint, stdout);
  6117.           }
  6118. #endif
  6119.         if (!rx_compactify_nfa (&rxb->rx, &mem, &size))
  6120.           return REG_ESPACE;
  6121.         rxb->buffer = mem;
  6122.         rxb->allocated = size;
  6123.         rxb->rx.buffer = mem;
  6124.         rxb->rx.allocated = size;
  6125.         perm_mem = ((char *)rxb->rx.buffer
  6126.             + rxb->rx.allocated - rxb->rx.reserved);
  6127.         rxb->se_params = ((struct re_se_params *)perm_mem);
  6128.         bcopy (params, rxb->se_params, iterator_size);
  6129.         perm_mem += iterator_size;
  6130.         rxb->fastset = (rx_Bitset) perm_mem;
  6131.         rxb->start = rx_id_to_nfa_state (&rxb->rx, start_id);
  6132.       }
  6133.     rx_bitset_null (rxb->rx.local_cset_size, rxb->fastset);
  6134.     rxb->can_match_empty = compute_fastset (rxb, orig_rexp);
  6135.     rxb->match_regs_on_stack =
  6136.       registers_on_stack (rxb, orig_rexp, 0, params); 
  6137.     rxb->search_regs_on_stack =
  6138.       registers_on_stack (rxb, fewer_side_effects, 0, params);
  6139.     if (rxb->can_match_empty)
  6140.       rx_bitset_universe (rxb->rx.local_cset_size, rxb->fastset);
  6141.     rxb->is_anchored = is_anchored (orig_rexp, (rx_side_effect) re_se_hat);
  6142.     rxb->begbuf_only = is_anchored (orig_rexp,
  6143.                     (rx_side_effect) re_se_begbuf);
  6144.       }
  6145.     rx_free_rexp (&rxb->rx, rexp);
  6146.     if (params)
  6147.       free (params);
  6148. #ifdef RX_DEBUG
  6149.     if (rx_debug_compile)
  6150.       {
  6151.     dbug_rxb = rxb;
  6152.     fputs ("...which cooks down to: \n", stdout);
  6153.     print_nfa (&rxb->rx, rxb->rx.nfa_states, re_seprint, stdout);
  6154.       }
  6155. #endif
  6156.   }
  6157.   return REG_NOERROR;
  6158. }
  6159.  
  6160.  
  6161.  
  6162. /* This table gives an error message for each of the error codes listed
  6163.    in regex.h.  Obviously the order here has to be same as there.  */
  6164.  
  6165. __const__ char * rx_error_msg[] =
  6166. { 0,                        /* REG_NOERROR */
  6167.     "No match",                    /* REG_NOMATCH */
  6168.     "Invalid regular expression",        /* REG_BADPAT */
  6169.     "Invalid collation character",        /* REG_ECOLLATE */
  6170.     "Invalid character class name",        /* REG_ECTYPE */
  6171.     "Trailing backslash",            /* REG_EESCAPE */
  6172.     "Invalid back reference",            /* REG_ESUBREG */
  6173.     "Unmatched [ or [^",            /* REG_EBRACK */
  6174.     "Unmatched ( or \\(",            /* REG_EPAREN */
  6175.     "Unmatched \\{",                /* REG_EBRACE */
  6176.     "Invalid content of \\{\\}",        /* REG_BADBR */
  6177.     "Invalid range end",            /* REG_ERANGE */
  6178.     "Memory exhausted",                /* REG_ESPACE */
  6179.     "Invalid preceding regular expression",    /* REG_BADRPT */
  6180.     "Premature end of regular expression",    /* REG_EEND */
  6181.     "Regular expression too big",        /* REG_ESIZE */
  6182.     "Unmatched ) or \\)",            /* REG_ERPAREN */
  6183. };
  6184.  
  6185.  
  6186.  
  6187.  
  6188. char rx_slowmap [256] =
  6189. {
  6190.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6191.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6192.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6193.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6194.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6195.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6196.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6197.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6198.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6199.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6200.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6201.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6202.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6203.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6204.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6205.   1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  6206. };
  6207.  
  6208. #ifdef __STDC__
  6209. RX_DECL void
  6210. rx_blow_up_fastmap (struct re_pattern_buffer * rxb)
  6211. #else
  6212. RX_DECL void
  6213. rx_blow_up_fastmap (rxb)
  6214.      struct re_pattern_buffer * rxb;
  6215. #endif
  6216. {
  6217.   int x;
  6218.   for (x = 0; x < 256; ++x)    /* &&&& 3.6 % */
  6219.     rxb->fastmap [x] = !!RX_bitset_member (rxb->fastset, x);
  6220.   rxb->fastmap_accurate = 1;
  6221. }
  6222.  
  6223.  
  6224.  
  6225.  
  6226. #if !defined(REGEX_MALLOC) && !defined(__GNUC__)
  6227. #define RE_SEARCH_2_FN    inner_re_search_2
  6228. #define RE_S2_QUAL static
  6229. #else
  6230. #define RE_SEARCH_2_FN    re_search_2
  6231. #define RE_S2_QUAL 
  6232. #endif
  6233.  
  6234. struct re_search_2_closure
  6235. {
  6236.   __const__ char * string1;
  6237.   int size1;
  6238.   __const__ char * string2;
  6239.   int size2;
  6240. };
  6241.  
  6242.  
  6243. static __inline__ enum rx_get_burst_return
  6244. re_search_2_get_burst (pos, vclosure, stop)
  6245.      struct rx_string_position * pos;
  6246.      void * vclosure;
  6247.      int stop;
  6248. {
  6249.   struct re_search_2_closure * closure;
  6250.   closure = (struct re_search_2_closure *)vclosure;
  6251.   if (!closure->string2)
  6252.     {
  6253.       int inset;
  6254.  
  6255.       inset = pos->pos - pos->string;
  6256.       if ((inset < 0) || (inset > closure->size1))
  6257.     return rx_get_burst_no_more;
  6258.       else
  6259.     {
  6260.       pos->pos = closure->string1 + inset;
  6261.       pos->string = closure->string1;
  6262.       pos->size = closure->size1;
  6263.       pos->end = ((__const__ unsigned char *)
  6264.               MIN(closure->string1 + closure->size1,
  6265.               closure->string1 + stop));
  6266.       pos->offset = 0;
  6267.       return ((pos->pos < pos->end)
  6268.           ? rx_get_burst_ok
  6269.           :  rx_get_burst_no_more);
  6270.     }
  6271.     }
  6272.   else if (!closure->string1)
  6273.     {
  6274.       int inset;
  6275.  
  6276.       inset = pos->pos - pos->string;
  6277.       pos->pos = closure->string2 + inset;
  6278.       pos->string = closure->string2;
  6279.       pos->size = closure->size2;
  6280.       pos->end = ((__const__ unsigned char *)
  6281.           MIN(closure->string2 + closure->size2,
  6282.               closure->string2 + stop));
  6283.       pos->offset = 0;
  6284.       return ((pos->pos < pos->end)
  6285.           ? rx_get_burst_ok
  6286.           :  rx_get_burst_no_more);
  6287.     }
  6288.   else
  6289.     {
  6290.       int inset;
  6291.  
  6292.       inset = pos->pos - pos->string;
  6293.       if (inset < closure->size1)
  6294.     {
  6295.       pos->pos = closure->string1 + inset;
  6296.       pos->string = closure->string1;
  6297.       pos->size = closure->size1;
  6298.       pos->end = ((__const__ unsigned char *)
  6299.               MIN(closure->string1 + closure->size1,
  6300.               closure->string1 + stop));
  6301.       pos->offset = 0;
  6302.       return rx_get_burst_ok;
  6303.     }
  6304.       else
  6305.     {
  6306.       pos->pos = closure->string2 + inset - closure->size1;
  6307.       pos->string = closure->string2;
  6308.       pos->size = closure->size2;
  6309.       pos->end = ((__const__ unsigned char *)
  6310.               MIN(closure->string2 + closure->size2,
  6311.               closure->string2 + stop - closure->size1));
  6312.       pos->offset = closure->size1;
  6313.       return ((pos->pos < pos->end)
  6314.           ? rx_get_burst_ok
  6315.           :  rx_get_burst_no_more);
  6316.     }
  6317.     }
  6318. }
  6319.  
  6320.  
  6321. static __inline__ enum rx_back_check_return
  6322. re_search_2_back_check (pos, lparen, rparen, translate, vclosure, stop)
  6323.      struct rx_string_position * pos;
  6324.      int lparen;
  6325.      int rparen;
  6326.      unsigned char * translate;
  6327.      void * vclosure;
  6328.      int stop;
  6329. {
  6330.   struct rx_string_position there;
  6331.   struct rx_string_position past;
  6332.  
  6333.   there = *pos;
  6334.   there.pos = there.string + lparen - there.offset;
  6335.   re_search_2_get_burst (&there, vclosure, stop);
  6336.  
  6337.   past = *pos;
  6338.   past.pos = past.string + rparen - there.offset;
  6339.   re_search_2_get_burst (&past, vclosure, stop);
  6340.  
  6341.   ++pos->pos;
  6342.   re_search_2_get_burst (pos, vclosure, stop);
  6343.  
  6344.   while (   (there.pos != past.pos)
  6345.      && (pos->pos != pos->end))
  6346.     if (TRANSLATE(*there.pos) != TRANSLATE(*pos->pos))
  6347.       return rx_back_check_fail;
  6348.     else
  6349.       {
  6350.     ++there.pos;
  6351.     ++pos->pos;
  6352.     if (there.pos == there.end)
  6353.       re_search_2_get_burst (&there, vclosure, stop);
  6354.     if (pos->pos == pos->end)
  6355.       re_search_2_get_burst (pos, vclosure, stop);
  6356.       }
  6357.  
  6358.   if (there.pos != past.pos)
  6359.     return rx_back_check_fail;
  6360.   --pos->pos;
  6361.   re_search_2_get_burst (pos, vclosure, stop);
  6362.   return rx_back_check_pass;
  6363. }
  6364.  
  6365. static __inline__ int
  6366. re_search_2_fetch_char (pos, offset, app_closure, stop)
  6367.      struct rx_string_position * pos;
  6368.      int offset;
  6369.      void * app_closure;
  6370.      int stop;
  6371. {
  6372.   struct re_search_2_closure * closure;
  6373.   closure = (struct re_search_2_closure *)app_closure;
  6374.   if (offset == 0)
  6375.     return *pos->pos;
  6376.   if (pos->pos == pos->end)
  6377.     return *closure->string2;
  6378.   else
  6379.     return *pos->pos;
  6380. }
  6381.      
  6382.  
  6383. #ifdef __STDC__
  6384. RE_S2_QUAL int
  6385. RE_SEARCH_2_FN (struct re_pattern_buffer *rxb,
  6386.         __const__ char * string1, int size1,
  6387.         __const__ char * string2, int size2,
  6388.         int startpos, int range,
  6389.         struct re_registers *regs,
  6390.         int stop)
  6391. #else
  6392. RE_S2_QUAL int
  6393. RE_SEARCH_2_FN (rxb,
  6394.         string1, size1, string2, size2, startpos, range, regs, stop)
  6395.      struct re_pattern_buffer *rxb;
  6396.      __const__ char * string1;
  6397.      int size1;
  6398.      __const__ char * string2;
  6399.      int size2;
  6400.      int startpos;
  6401.      int range;
  6402.      struct re_registers *regs;
  6403.      int stop;
  6404. #endif
  6405. {
  6406.   int answer;
  6407.   struct re_search_2_closure closure;
  6408.   closure.string1 = string1;
  6409.   closure.size1 = size1;
  6410.   closure.string2 = string2;
  6411.   closure.size2 = size2;
  6412.   answer = rx_search (rxb, startpos, range, stop, size1 + size2,
  6413.               re_search_2_get_burst,
  6414.               re_search_2_back_check,
  6415.               re_search_2_fetch_char,
  6416.               (void *)&closure,
  6417.               regs,
  6418.               0,
  6419.               0);
  6420.   switch (answer)
  6421.     {
  6422.     case rx_search_continuation:
  6423.       abort ();
  6424.     case rx_search_error:
  6425.       return -2;
  6426.     case rx_search_soft_fail:
  6427.     case rx_search_fail:
  6428.       return -1;
  6429.     default:
  6430.       return answer;
  6431.     }
  6432. }
  6433.  
  6434. /* Export rx_search to callers outside this file.  */
  6435.  
  6436. int
  6437. re_rx_search (rxb, startpos, range, stop, total_size,
  6438.           get_burst, back_check, fetch_char,
  6439.           app_closure, regs, resume_state, save_state)
  6440.      struct re_pattern_buffer * rxb;
  6441.      int startpos;
  6442.      int range;
  6443.      int stop;
  6444.      int total_size;
  6445.      rx_get_burst_fn get_burst;
  6446.      rx_back_check_fn back_check;
  6447.      rx_fetch_char_fn fetch_char;
  6448.      void * app_closure;
  6449.      struct re_registers * regs;
  6450.      struct rx_search_state * resume_state;
  6451.      struct rx_search_state * save_state;
  6452. {
  6453.   return rx_search (rxb, startpos, range, stop, total_size,
  6454.             get_burst, back_check, fetch_char, app_closure,
  6455.             regs, resume_state, save_state);
  6456. }
  6457.  
  6458. #if !defined(REGEX_MALLOC) && !defined(__GNUC__)
  6459. #ifdef __STDC__
  6460. int
  6461. re_search_2 (struct re_pattern_buffer *rxb,
  6462.          __const__ char * string1, int size1,
  6463.          __const__ char * string2, int size2,
  6464.          int startpos, int range,
  6465.          struct re_registers *regs,
  6466.          int stop)
  6467. #else
  6468. int
  6469. re_search_2 (rxb, string1, size1, string2, size2, startpos, range, regs, stop)
  6470.      struct re_pattern_buffer *rxb;
  6471.      __const__ char * string1;
  6472.      int size1;
  6473.      __const__ char * string2;
  6474.      int size2;
  6475.      int startpos;
  6476.      int range;
  6477.      struct re_registers *regs;
  6478.      int stop;
  6479. #endif
  6480. {
  6481.   int ret;
  6482.   ret = inner_re_search_2 (rxb, string1, size1, string2, size2, startpos,
  6483.                range, regs, stop);
  6484.   alloca (0);
  6485.   return ret;
  6486. }
  6487. #endif
  6488.  
  6489.  
  6490. /* Like re_search_2, above, but only one string is specified, and
  6491.  * doesn't let you say where to stop matching.
  6492.  */
  6493.  
  6494. #ifdef __STDC__
  6495. int
  6496. re_search (struct re_pattern_buffer * rxb, __const__ char *string,
  6497.        int size, int startpos, int range,
  6498.        struct re_registers *regs)
  6499. #else
  6500. int
  6501. re_search (rxb, string, size, startpos, range, regs)
  6502.      struct re_pattern_buffer * rxb;
  6503.      __const__ char * string;
  6504.      int size;
  6505.      int startpos;
  6506.      int range;
  6507.      struct re_registers *regs;
  6508. #endif
  6509. {
  6510.   return re_search_2 (rxb, 0, 0, string, size, startpos, range, regs, size);
  6511. }
  6512.  
  6513. #ifdef __STDC__
  6514. int
  6515. re_match_2 (struct re_pattern_buffer * rxb,
  6516.         __const__ char * string1, int size1,
  6517.         __const__ char * string2, int size2,
  6518.         int pos, struct re_registers *regs, int stop)
  6519. #else
  6520. int
  6521. re_match_2 (rxb, string1, size1, string2, size2, pos, regs, stop)
  6522.      struct re_pattern_buffer * rxb;
  6523.      __const__ char * string1;
  6524.      int size1;
  6525.      __const__ char * string2;
  6526.      int size2;
  6527.      int pos;
  6528.      struct re_registers *regs;
  6529.      int stop;
  6530. #endif
  6531. {
  6532.   struct re_registers some_regs;
  6533.   regoff_t start;
  6534.   regoff_t end;
  6535.   int srch;
  6536.   int save = rxb->regs_allocated;
  6537.   struct re_registers * regs_to_pass = regs;
  6538.  
  6539.   if (!regs)
  6540.     {
  6541.       some_regs.start = &start;
  6542.       some_regs.end = &end;
  6543.       some_regs.num_regs = 1;
  6544.       regs_to_pass = &some_regs;
  6545.       rxb->regs_allocated = REGS_FIXED;
  6546.     }
  6547.  
  6548.   srch = re_search_2 (rxb, string1, size1, string2, size2,
  6549.               pos, 1, regs_to_pass, stop);
  6550.   if (regs_to_pass != regs)
  6551.     rxb->regs_allocated = save;
  6552.   if (srch < 0)
  6553.     return srch;
  6554.   return regs_to_pass->end[0] - regs_to_pass->start[0];
  6555. }
  6556.  
  6557. /* re_match is like re_match_2 except it takes only a single string.  */
  6558.  
  6559. #ifdef __STDC__
  6560. int
  6561. re_match (struct re_pattern_buffer * rxb,
  6562.       __const__ char * string,
  6563.       int size, int pos,
  6564.       struct re_registers *regs)
  6565. #else
  6566. int
  6567. re_match (rxb, string, size, pos, regs)
  6568.      struct re_pattern_buffer * rxb;
  6569.      __const__ char *string;
  6570.      int size;
  6571.      int pos;
  6572.      struct re_registers *regs;
  6573. #endif
  6574. {
  6575.   return re_match_2 (rxb, string, size, 0, 0, pos, regs, size);
  6576. }
  6577.  
  6578.  
  6579.  
  6580. /* Set by `re_set_syntax' to the current regexp syntax to recognize.  Can
  6581.    also be assigned to arbitrarily: each pattern buffer stores its own
  6582.    syntax, so it can be changed between regex compilations.  */
  6583. reg_syntax_t re_syntax_options = RE_SYNTAX_EMACS;
  6584.  
  6585.  
  6586. /* Specify the precise syntax of regexps for compilation.  This provides
  6587.    for compatibility for various utilities which historically have
  6588.    different, incompatible syntaxes.
  6589.  
  6590.    The argument SYNTAX is a bit mask comprised of the various bits
  6591.    defined in regex.h.  We return the old syntax.  */
  6592.  
  6593. #ifdef __STDC__
  6594. reg_syntax_t
  6595. re_set_syntax (reg_syntax_t syntax)
  6596. #else
  6597. reg_syntax_t
  6598. re_set_syntax (syntax)
  6599.     reg_syntax_t syntax;
  6600. #endif
  6601. {
  6602.   reg_syntax_t ret = re_syntax_options;
  6603.  
  6604.   re_syntax_options = syntax;
  6605.   return ret;
  6606. }
  6607.  
  6608.  
  6609. /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
  6610.    ENDS.  Subsequent matches using PATTERN_BUFFER and REGS will use
  6611.    this memory for recording register information.  STARTS and ENDS
  6612.    must be allocated using the malloc library routine, and must each
  6613.    be at least NUM_REGS * sizeof (regoff_t) bytes long.
  6614.  
  6615.    If NUM_REGS == 0, then subsequent matches should allocate their own
  6616.    register data.
  6617.  
  6618.    Unless this function is called, the first search or match using
  6619.    PATTERN_BUFFER will allocate its own register data, without
  6620.    freeing the old data.  */
  6621.  
  6622. #ifdef __STDC__
  6623. void
  6624. re_set_registers (struct re_pattern_buffer *bufp,
  6625.           struct re_registers *regs,
  6626.           unsigned num_regs,
  6627.           regoff_t * starts, regoff_t * ends)
  6628. #else
  6629. void
  6630. re_set_registers (bufp, regs, num_regs, starts, ends)
  6631.      struct re_pattern_buffer *bufp;
  6632.      struct re_registers *regs;
  6633.      unsigned num_regs;
  6634.      regoff_t * starts;
  6635.      regoff_t * ends;
  6636. #endif
  6637. {
  6638.   if (num_regs)
  6639.     {
  6640.       bufp->regs_allocated = REGS_REALLOCATE;
  6641.       regs->num_regs = num_regs;
  6642.       regs->start = starts;
  6643.       regs->end = ends;
  6644.     }
  6645.   else
  6646.     {
  6647.       bufp->regs_allocated = REGS_UNALLOCATED;
  6648.       regs->num_regs = 0;
  6649.       regs->start = regs->end = (regoff_t) 0;
  6650.     }
  6651. }
  6652.  
  6653.  
  6654.  
  6655.  
  6656. #ifdef __STDC__
  6657. static int 
  6658. cplx_se_sublist_len (struct rx_se_list * list)
  6659. #else
  6660. static int 
  6661. cplx_se_sublist_len (list)
  6662.      struct rx_se_list * list;
  6663. #endif
  6664. {
  6665.   int x = 0;
  6666.   while (list)
  6667.     {
  6668.       if ((long)list->car >= 0)
  6669.     ++x;
  6670.       list = list->cdr;
  6671.     }
  6672.   return x;
  6673. }
  6674.  
  6675.  
  6676. /* For rx->se_list_cmp */
  6677.  
  6678. #ifdef __STDC__
  6679. static int 
  6680. posix_se_list_order (struct rx * rx,
  6681.              struct rx_se_list * a, struct rx_se_list * b)
  6682. #else
  6683. static int 
  6684. posix_se_list_order (rx, a, b)
  6685.      struct rx * rx;
  6686.      struct rx_se_list * a;
  6687.      struct rx_se_list * b;
  6688. #endif
  6689. {
  6690.   int al = cplx_se_sublist_len (a);
  6691.   int bl = cplx_se_sublist_len (b);
  6692.  
  6693.   if (!al && !bl)
  6694.     return ((a == b)
  6695.         ? 0
  6696.         : ((a < b) ? -1 : 1));
  6697.   
  6698.   else if (!al)
  6699.     return -1;
  6700.  
  6701.   else if (!bl)
  6702.     return 1;
  6703.  
  6704.   else
  6705.     {
  6706.       rx_side_effect * av = ((rx_side_effect *)
  6707.                  alloca (sizeof (rx_side_effect) * (al + 1)));
  6708.       rx_side_effect * bv = ((rx_side_effect *)
  6709.                  alloca (sizeof (rx_side_effect) * (bl + 1)));
  6710.       struct rx_se_list * ap = a;
  6711.       struct rx_se_list * bp = b;
  6712.       int ai, bi;
  6713.       
  6714.       for (ai = al - 1; ai >= 0; --ai)
  6715.     {
  6716.       while ((long)ap->car < 0)
  6717.         ap = ap->cdr;
  6718.       av[ai] = ap->car;
  6719.       ap = ap->cdr;
  6720.     }
  6721.       av[al] = (rx_side_effect)-2;
  6722.       for (bi = bl - 1; bi >= 0; --bi)
  6723.     {
  6724.       while ((long)bp->car < 0)
  6725.         bp = bp->cdr;
  6726.       bv[bi] = bp->car;
  6727.       bp = bp->cdr;
  6728.     }
  6729.       bv[bl] = (rx_side_effect)-1;
  6730.  
  6731.       {
  6732.     int ret;
  6733.     int x = 0;
  6734.     while (av[x] == bv[x])
  6735.       ++x;
  6736.      ret = (((unsigned *)(av[x]) < (unsigned *)(bv[x])) ? -1 : 1);
  6737.     return ret;
  6738.       }
  6739.     }
  6740. }
  6741.  
  6742.  
  6743.  
  6744.  
  6745. /* re_compile_pattern is the GNU regular expression compiler: it
  6746.    compiles PATTERN (of length SIZE) and puts the result in RXB.
  6747.    Returns 0 if the pattern was valid, otherwise an error string.
  6748.  
  6749.    Assumes the `allocated' (and perhaps `buffer') and `translate' fields
  6750.    are set in RXB on entry.
  6751.  
  6752.    We call rx_compile to do the actual compilation.  */
  6753.  
  6754. #ifdef __STDC__
  6755. __const__ char *
  6756. re_compile_pattern (__const__ char *pattern,
  6757.             int length,
  6758.             struct re_pattern_buffer * rxb)
  6759. #else
  6760. __const__ char *
  6761. re_compile_pattern (pattern, length, rxb)
  6762.      __const__ char *pattern;
  6763.      int length;
  6764.      struct re_pattern_buffer * rxb;
  6765. #endif
  6766. {
  6767.   reg_errcode_t ret;
  6768.  
  6769.   /* GNU code is written to assume at least RE_NREGS registers will be set
  6770.      (and at least one extra will be -1).  */
  6771.   rxb->regs_allocated = REGS_UNALLOCATED;
  6772.  
  6773.   /* And GNU code determines whether or not to get register information
  6774.      by passing null for the REGS argument to re_match, etc., not by
  6775.      setting no_sub.  */
  6776.   rxb->no_sub = 0;
  6777.  
  6778.   rxb->rx.local_cset_size = 256;
  6779.  
  6780.   /* Match anchors at newline.  */
  6781.   rxb->newline_anchor = 1;
  6782.  
  6783.   rxb->re_nsub = 0;
  6784.   rxb->start = 0;
  6785.   rxb->se_params = 0;
  6786.   rxb->rx.nodec = 0;
  6787.   rxb->rx.epsnodec = 0;
  6788.   rxb->rx.instruction_table = 0;
  6789.   rxb->rx.nfa_states = 0;
  6790.   rxb->rx.se_list_cmp = posix_se_list_order;
  6791.   rxb->rx.start_set = 0;
  6792.  
  6793.   ret = rx_compile (pattern, length, re_syntax_options, rxb);
  6794.   alloca (0);
  6795.   return rx_error_msg[(int) ret];
  6796. }
  6797.  
  6798.  
  6799.  
  6800. #ifdef __STDC__
  6801. int
  6802. re_compile_fastmap (struct re_pattern_buffer * rxb)
  6803. #else
  6804. int
  6805. re_compile_fastmap (rxb)
  6806.      struct re_pattern_buffer * rxb;
  6807. #endif
  6808. {
  6809.   rx_blow_up_fastmap (rxb);
  6810.   return 0;
  6811. }
  6812.  
  6813.  
  6814.  
  6815.  
  6816. /* Entry points compatible with 4.2 BSD regex library.  We don't define
  6817.    them if this is an Emacs or POSIX compilation.  */
  6818.  
  6819. #if (!defined (emacs) && !defined (_POSIX_SOURCE)) || defined(USE_BSD_REGEX)
  6820.  
  6821. /* BSD has one and only one pattern buffer.  */
  6822. static struct re_pattern_buffer rx_comp_buf;
  6823.  
  6824. #ifdef __STDC__
  6825. char *
  6826. re_comp (__const__ char *s)
  6827. #else
  6828. char *
  6829. re_comp (s)
  6830.     __const__ char *s;
  6831. #endif
  6832. {
  6833.   reg_errcode_t ret;
  6834.  
  6835.   if (!s || (*s == '\0'))
  6836.     {
  6837.       if (!rx_comp_buf.buffer)
  6838.     return "No previous regular expression";
  6839.       return 0;
  6840.     }
  6841.  
  6842.   if (!rx_comp_buf.fastmap)
  6843.     {
  6844.       rx_comp_buf.fastmap = (char *) malloc (1 << CHARBITS);
  6845.       if (!rx_comp_buf.fastmap)
  6846.     return "Memory exhausted";
  6847.     }
  6848.  
  6849.   /* Since `rx_exec' always passes NULL for the `regs' argument, we
  6850.      don't need to initialize the pattern buffer fields which affect it.  */
  6851.  
  6852.   /* Match anchors at newlines.  */
  6853.   rx_comp_buf.newline_anchor = 1;
  6854.  
  6855.   rx_comp_buf.re_nsub = 0;
  6856.   rx_comp_buf.start = 0;
  6857.   rx_comp_buf.se_params = 0;
  6858.   rx_comp_buf.rx.nodec = 0;
  6859.   rx_comp_buf.rx.epsnodec = 0;
  6860.   rx_comp_buf.rx.instruction_table = 0;
  6861.   rx_comp_buf.rx.nfa_states = 0;
  6862.   rx_comp_buf.rx.local_cset_size = 256;
  6863.   rx_comp_buf.rx.start = 0;
  6864.   rx_comp_buf.rx.se_list_cmp = posix_se_list_order;
  6865.   rx_comp_buf.rx.start_set = 0;
  6866.  
  6867.   ret = rx_compile (s, strlen (s), re_syntax_options, &rx_comp_buf);
  6868.   alloca (0);
  6869.  
  6870.   /* Yes, we're discarding `__const__' here.  */
  6871.   return (char *) rx_error_msg[(int) ret];
  6872. }
  6873.  
  6874.  
  6875. #ifdef __STDC__
  6876. int
  6877. re_exec (__const__ char *s)
  6878. #else
  6879. int
  6880. re_exec (s)
  6881.     __const__ char *s;
  6882. #endif
  6883. {
  6884.   __const__ int len = strlen (s);
  6885.   return
  6886.     0 <= re_search (&rx_comp_buf, s, len, 0, len, (struct re_registers *) 0);
  6887. }
  6888. #endif /* not emacs and not _POSIX_SOURCE */
  6889.  
  6890.  
  6891.  
  6892. /* POSIX.2 functions.  Don't define these for Emacs.  */
  6893.  
  6894. #if !defined(emacs)
  6895.  
  6896. /* regcomp takes a regular expression as a string and compiles it.
  6897.  
  6898.    PREG is a regex_t *.  We do not expect any fields to be initialized,
  6899.    since POSIX says we shouldn't.  Thus, we set
  6900.  
  6901.      `buffer' to the compiled pattern;
  6902.      `used' to the length of the compiled pattern;
  6903.      `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
  6904.        REG_EXTENDED bit in CFLAGS is set; otherwise, to
  6905.        RE_SYNTAX_POSIX_BASIC;
  6906.      `newline_anchor' to REG_NEWLINE being set in CFLAGS;
  6907.      `fastmap' and `fastmap_accurate' to zero;
  6908.      `re_nsub' to the number of subexpressions in PATTERN.
  6909.  
  6910.    PATTERN is the address of the pattern string.
  6911.  
  6912.    CFLAGS is a series of bits which affect compilation.
  6913.  
  6914.      If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
  6915.      use POSIX basic syntax.
  6916.  
  6917.      If REG_NEWLINE is set, then . and [^...] don't match newline.
  6918.      Also, regexec will try a match beginning after every newline.
  6919.  
  6920.      If REG_ICASE is set, then we considers upper- and lowercase
  6921.      versions of letters to be equivalent when matching.
  6922.  
  6923.      If REG_NOSUB is set, then when PREG is passed to regexec, that
  6924.      routine will report only success or failure, and nothing about the
  6925.      registers.
  6926.  
  6927.    It returns 0 if it succeeds, nonzero if it doesn't.  (See regex.h for
  6928.    the return codes and their meanings.)  */
  6929.  
  6930.  
  6931. #ifdef __STDC__
  6932. int
  6933. regcomp (regex_t * preg, __const__ char * pattern, int cflags)
  6934. #else
  6935. int
  6936. regcomp (preg, pattern, cflags)
  6937.     regex_t * preg;
  6938.     __const__ char * pattern;
  6939.     int cflags;
  6940. #endif
  6941. {
  6942.   reg_errcode_t ret;
  6943.   unsigned syntax
  6944.     = cflags & REG_EXTENDED ? RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
  6945.  
  6946.   /* regex_compile will allocate the space for the compiled pattern.  */
  6947.   preg->buffer = 0;
  6948.   preg->allocated = 0;
  6949.  
  6950.   preg->fastmap = malloc (256);
  6951.   if (!preg->fastmap)
  6952.     return REG_ESPACE;
  6953.   preg->fastmap_accurate = 0;
  6954.  
  6955.   if (cflags & REG_ICASE)
  6956.     {
  6957.       unsigned i;
  6958.  
  6959.       preg->translate = (unsigned char *) malloc (256);
  6960.       if (!preg->translate)
  6961.         return (int) REG_ESPACE;
  6962.  
  6963.       /* Map uppercase characters to corresponding lowercase ones.  */
  6964.       for (i = 0; i < CHAR_SET_SIZE; i++)
  6965.         preg->translate[i] = isupper (i) ? tolower (i) : i;
  6966.     }
  6967.   else
  6968.     preg->translate = 0;
  6969.  
  6970.   /* If REG_NEWLINE is set, newlines are treated differently.  */
  6971.   if (cflags & REG_NEWLINE)
  6972.     { /* REG_NEWLINE implies neither . nor [^...] match newline.  */
  6973.       syntax &= ~RE_DOT_NEWLINE;
  6974.       syntax |= RE_HAT_LISTS_NOT_NEWLINE;
  6975.       /* It also changes the matching behavior.  */
  6976.       preg->newline_anchor = 1;
  6977.     }
  6978.   else
  6979.     preg->newline_anchor = 0;
  6980.  
  6981.   preg->no_sub = !!(cflags & REG_NOSUB);
  6982.  
  6983.   /* POSIX says a null character in the pattern terminates it, so we
  6984.      can use strlen here in compiling the pattern.  */
  6985.   preg->re_nsub = 0;
  6986.   preg->start = 0;
  6987.   preg->se_params = 0;
  6988.   preg->rx.nodec = 0;
  6989.   preg->rx.epsnodec = 0;
  6990.   preg->rx.instruction_table = 0;
  6991.   preg->rx.nfa_states = 0;
  6992.   preg->rx.local_cset_size = 256;
  6993.   preg->rx.start = 0;
  6994.   preg->rx.se_list_cmp = posix_se_list_order;
  6995.   preg->rx.start_set = 0;
  6996.   ret = rx_compile (pattern, strlen (pattern), syntax, preg);
  6997.   alloca (0);
  6998.  
  6999.   /* POSIX doesn't distinguish between an unmatched open-group and an
  7000.      unmatched close-group: both are REG_EPAREN.  */
  7001.   if (ret == REG_ERPAREN) ret = REG_EPAREN;
  7002.  
  7003.   return (int) ret;
  7004. }
  7005.  
  7006.  
  7007. /* regexec searches for a given pattern, specified by PREG, in the
  7008.    string STRING.
  7009.  
  7010.    If NMATCH is zero or REG_NOSUB was set in the cflags argument to
  7011.    `regcomp', we ignore PMATCH.  Otherwise, we assume PMATCH has at
  7012.    least NMATCH elements, and we set them to the offsets of the
  7013.    corresponding matched substrings.
  7014.  
  7015.    EFLAGS specifies `execution flags' which affect matching: if
  7016.    REG_NOTBOL is set, then ^ does not match at the beginning of the
  7017.    string; if REG_NOTEOL is set, then $ does not match at the end.
  7018.  
  7019.    We return 0 if we find a match and REG_NOMATCH if not.  */
  7020.  
  7021. #ifdef __STDC__
  7022. int
  7023. regexec (__const__ regex_t *preg, __const__ char *string,
  7024.      size_t nmatch, regmatch_t pmatch[],
  7025.      int eflags)
  7026. #else
  7027. int
  7028. regexec (preg, string, nmatch, pmatch, eflags)
  7029.     __const__ regex_t *preg;
  7030.     __const__ char *string;
  7031.     size_t nmatch;
  7032.     regmatch_t pmatch[];
  7033.     int eflags;
  7034. #endif
  7035. {
  7036.   int ret;
  7037.   struct re_registers regs;
  7038.   regex_t private_preg;
  7039.   int len = strlen (string);
  7040.   boolean want_reg_info = !preg->no_sub && nmatch > 0;
  7041.  
  7042.   private_preg = *preg;
  7043.  
  7044.   private_preg.not_bol = !!(eflags & REG_NOTBOL);
  7045.   private_preg.not_eol = !!(eflags & REG_NOTEOL);
  7046.  
  7047.   /* The user has told us exactly how many registers to return
  7048.    * information about, via `nmatch'.  We have to pass that on to the
  7049.    * matching routines.
  7050.    */
  7051.   private_preg.regs_allocated = REGS_FIXED;
  7052.  
  7053.   if (want_reg_info)
  7054.     {
  7055.       regs.num_regs = nmatch;
  7056.       regs.start =  (( regoff_t *) malloc ((nmatch) * sizeof ( regoff_t)));
  7057.       regs.end =  (( regoff_t *) malloc ((nmatch) * sizeof ( regoff_t)));
  7058.       if (regs.start == 0 || regs.end == 0)
  7059.         return (int) REG_NOMATCH;
  7060.     }
  7061.  
  7062.   /* Perform the searching operation.  */
  7063.   ret = re_search (&private_preg,
  7064.            string, len,
  7065.                    /* start: */ 0,
  7066.            /* range: */ len,
  7067.                    want_reg_info ? ®s : (struct re_registers *) 0);
  7068.  
  7069.   /* Copy the register information to the POSIX structure.  */
  7070.   if (want_reg_info)
  7071.     {
  7072.       if (ret >= 0)
  7073.         {
  7074.           unsigned r;
  7075.  
  7076.           for (r = 0; r < nmatch; r++)
  7077.             {
  7078.               pmatch[r].rm_so = regs.start[r];
  7079.               pmatch[r].rm_eo = regs.end[r];
  7080.             }
  7081.         }
  7082.  
  7083.       /* If we needed the temporary register info, free the space now.  */
  7084.       free (regs.start);
  7085.       free (regs.end);
  7086.     }
  7087.  
  7088.   /* We want zero return to mean success, unlike `re_search'.  */
  7089.   return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
  7090. }
  7091.  
  7092.  
  7093. /* Returns a message corresponding to an error code, ERRCODE, returned
  7094.    from either regcomp or regexec.   */
  7095.  
  7096. #ifdef __STDC__
  7097. size_t
  7098. regerror (int errcode, __const__ regex_t *preg,
  7099.       char *errbuf, size_t errbuf_size)
  7100. #else
  7101. size_t
  7102. regerror (errcode, preg, errbuf, errbuf_size)
  7103.     int errcode;
  7104.     __const__ regex_t *preg;
  7105.     char *errbuf;
  7106.     size_t errbuf_size;
  7107. #endif
  7108. {
  7109.   __const__ char *msg
  7110.     = rx_error_msg[errcode] == 0 ? "Success" : rx_error_msg[errcode];
  7111.   size_t msg_size = strlen (msg) + 1; /* Includes the 0.  */
  7112.  
  7113.   if (errbuf_size != 0)
  7114.     {
  7115.       if (msg_size > errbuf_size)
  7116.         {
  7117.           strncpy (errbuf, msg, errbuf_size - 1);
  7118.           errbuf[errbuf_size - 1] = 0;
  7119.         }
  7120.       else
  7121.         strcpy (errbuf, msg);
  7122.     }
  7123.  
  7124.   return msg_size;
  7125. }
  7126.  
  7127.  
  7128. /* Free dynamically allocated space used by PREG.  */
  7129.  
  7130. #ifdef __STDC__
  7131. void
  7132. regfree (regex_t *preg)
  7133. #else
  7134. void
  7135. regfree (preg)
  7136.     regex_t *preg;
  7137. #endif
  7138. {
  7139.   if (preg->buffer != 0)
  7140.     free (preg->buffer);
  7141.   preg->buffer = 0;
  7142.   preg->allocated = 0;
  7143.  
  7144.   if (preg->fastmap != 0)
  7145.     free (preg->fastmap);
  7146.   preg->fastmap = 0;
  7147.   preg->fastmap_accurate = 0;
  7148.  
  7149.   if (preg->translate != 0)
  7150.     free (preg->translate);
  7151.   preg->translate = 0;
  7152. }
  7153.  
  7154. #endif /* not emacs  */
  7155.  
  7156.  
  7157.  
  7158.  
  7159.  
  7160.